package com.vca.service.service.Impl;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vca.common.constants.*;
import com.vca.common.exception.VcaException;
import com.vca.common.model.category.Category;
import com.vca.common.model.coupon.StoreCouponUser;
import com.vca.common.model.course.Course;
import com.vca.common.model.course.CoursePackage;
import com.vca.common.model.express.Express;
import com.vca.common.model.invoice.InvoiceOrderRelation;
import com.vca.common.model.invoice.InvoiceRecord;
import com.vca.common.model.order.StoreOrder;
import com.vca.common.model.order.StoreOrderInfo;
import com.vca.common.model.order.StoreOrderStatus;
import com.vca.common.model.product.StoreProduct;
import com.vca.common.model.product.StoreProductAttrValue;
import com.vca.common.model.sf.*;
import com.vca.common.model.sms.SmsTemplate;
import com.vca.common.model.system.SystemAdmin;
import com.vca.common.model.system.SystemConfig;
import com.vca.common.model.system.SystemNotification;
import com.vca.common.model.talk.Talk;
import com.vca.common.model.talk.TalkScheduling;
import com.vca.common.model.user.User;
import com.vca.common.model.user.UserAddress;
import com.vca.common.model.user.UserCard;
import com.vca.common.model.vca_product.VcaProduct;
import com.vca.common.page.CommonPage;
import com.vca.common.request.*;
import com.vca.common.response.*;
import com.vca.common.response.sf.ResponseCancel;
import com.vca.common.result.CommonResult;
import com.vca.common.utils.DateUtil;
import com.vca.common.utils.RedisUtil;
import com.vca.common.utils.VcaUtil;
import com.vca.common.vo.*;
import com.vca.service.delete.OrderUtils;
import com.vca.service.service.*;
import com.vca.service.util.SFUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * H5端订单操作
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Value("${vca.proxy.disable}")
    private Boolean disable;

    private final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private StoreOrderInfoService storeOrderInfoService;

    @Autowired
    private StoreOrderStatusService storeOrderStatusService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private StoreProductReplyService storeProductReplyService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private OrderUtils orderUtils;


    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private SystemAdminService systemAdminService;

    @Autowired
    private StoreProductService storeProductService;

    @Autowired
    private StoreProductAttrValueService attrValueService;

    @Autowired
    private StoreCouponUserService storeCouponUserService;

    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;

    @Autowired
    private ExpressService expressService;


    @Autowired
    private SystemNotificationService systemNotificationService;

    @Autowired
    private SmsTemplateService smsTemplateService;

    @Autowired
    private VcaProductService vcaProductService;

    @Autowired
    private UserCardService userCardService;

    @Autowired
    private SFService sfService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private CoursePackageService coursePackageService;

    @Autowired
    private TalkService talkService;

    @Autowired
    private TalkSchedulingService talkSchedulingService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SFUtil sfUtil;

    @Autowired
    private UmsPayService umsPayService;

    /**
     * 发送后台管理员下单提醒通知短信
     *
     * @param orderNo 订单编号
     */
    @Async
    public void sendAdminOrderNotice(String orderNo) {
        // 系统是否开启用户下单管理员提醒开关
        SystemNotification notification = systemNotificationService.getByMark(NotifyConstants.PLACE_AN_ORDER_ADMIN_MARK);
        if (!notification.getIsSms().equals(1)) {
            return;
        }
        // 查询可已发送短信的管理员
        List<SystemAdmin> systemAdminList = systemAdminService.findIsSmsList();
        if (CollUtil.isEmpty(systemAdminList)) {
            return;
        }
        // 发送短信
        SmsTemplate smsTemplate = smsTemplateService.getDetail(notification.getSmsId());
        Integer tempId = Integer.valueOf(smsTemplate.getTempId());
//        systemAdminList.forEach(admin -> smsService.sendCreateOrderNotice(admin.getPhone(), orderNo, admin.getRealName(), tempId));
    }

    /**
     * 删除已完成订单
     *
     * @param id Integer 订单id
     * @return 删除结果
     */
    @Override
    public Boolean delete(Integer id) {
        StoreOrder storeOrder = storeOrderService.getById(id);
        Integer userId = userService.getUserIdException();
        if (ObjectUtil.isNull(storeOrder) || !userId.equals(storeOrder.getUid())) {
            throw new VcaException("没有找到相关订单信息!");
        }
        if (storeOrder.getIsDel() || storeOrder.getIsSystemDel()) {
            throw new VcaException("订单已删除!");
        }
        if (storeOrder.getPaid()) {
            if (storeOrder.getRefundStatus() > 0 && !storeOrder.getRefundStatus().equals(2)) {
                throw new VcaException("订单在退款流程中无法删除!");
            }
            if (storeOrder.getRefundStatus().equals(0) && !storeOrder.getStatus().equals(3)) {
                throw new VcaException("只能删除已完成订单!");
            }
        } else {
            throw new VcaException("未支付订单无法删除!");
        }

        //可以删除
        storeOrder.setIsDel(true);
        Boolean execute = transactionTemplate.execute(e -> {
            storeOrderService.updateById(storeOrder);
            //日志
            storeOrderStatusService.createLog(storeOrder.getId(), "remove_order", 0,"删除订单");
            return Boolean.TRUE;
        });
        return execute;
    }

    /**
     * 创建订单商品评价
     *
     * @param request 请求参数
     * @return Boolean
     */
    @Override
    public Boolean reply(StoreProductReplyAddRequest request) {
        if (StrUtil.isBlank(request.getOrderNo())) {
            throw new VcaException("订单号参数不能为空");
        }
        return storeProductReplyService.create(request);
    }

    /**
     * 订单收货
     *
     * @param orderNo Integer 订单号
     */
    @Override
    public Boolean take(String orderNo) {

        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);
        if (ObjectUtil.isEmpty(storeOrder)){
            throw new VcaException("该订单不存在");
        }
        if (!Objects.equals(storeOrder.getUid(),userService.getUserId())){
            throw new VcaException("该订单不存在");
        }
        if (!storeOrder.getStatus().equals(Constants.ORDER_STATUS_INT_SPIKE)) {
            throw new VcaException("订单状态错误");
        }
        //已完成
        storeOrder.setStatus(Constants.ORDER_STATUS_INT_COMPLETE);
        storeOrder.setClosingTime(new Date());
        String afterSalesTime = systemConfigService.getValueByKey(Constants.AFTER_SALES_TIME);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date calendarTime = calendar.getTime();
        Date addDays = DateUtils.addDays(calendarTime, Integer.parseInt(afterSalesTime)+1);
        storeOrder.setAfterSalesDeadline(addDays);

        ArrayList<StoreOrderInfo> storeOrderInfos = new ArrayList<>();
        for (StoreOrderInfo storeOrderInfo : storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, storeOrder.getOrderId()))) {
            storeOrderInfo.setStatus(Constants.ORDER_STATUS_INT_COMPLETE);
            storeOrderInfos.add(storeOrderInfo);
        }

        Boolean execute = transactionTemplate.execute(e -> {
            storeOrderService.updateById(storeOrder);
            storeOrderInfoService.updateBatchById(storeOrderInfos);
            storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_LOG_SHOUHUO,0, "订单已收货");
            return Boolean.TRUE;
        });

        if (execute) {
            //后续操作放入redis
            sfService.orderTakePushMessage(storeOrder);
//            redisUtil.lPush(TaskConstants.ORDER_TASK_REDIS_KEY_AFTER_TAKE_BY_USER, storeOrder.getId());
        }
        return execute;
    }

    /**
     * 订单取消
     *
     * @param orderNo Integer 订单号
     */
    @Override
    public Boolean cancel(String orderNo) {
        User info = userService.getInfo();
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);
        if (ObjectUtil.isEmpty(storeOrder)){
            throw new VcaException("订单不存在");
        }
        if (!Objects.equals(storeOrder.getUid(),info.getUid())){
            throw new VcaException("订单不存在");
        }
        if (storeOrder.getPaid()) {
            throw new VcaException("该订单已支付");
        }
        if (storeOrder.getIsDel()){
            throw new VcaException("该订单已取消");
        }


        storeOrder.setIsDel(true);
        Boolean execute = transactionTemplate.execute(e->{
            storeOrderService.updateById(storeOrder);
            storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_LOG_CANCEL, 0,"订单取消");
            return Boolean.TRUE;
        });
        //后续操作放入redis
        if (execute){
            redisUtil.lPush(TaskConstants.ORDER_TASK_REDIS_KEY_FRONT_ORDER_CANCEL_BY_USER, storeOrder.getId());
        }

        return execute;
    }

    /**
     * 订单取消(商品)
     * @param orderId Integer 订单id
     */
    @Override
    public Boolean productCancel(String orderId) {
        User info = userService.getInfo();
        //订单
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderId);

        if (ObjectUtil.isEmpty(storeOrder)) {
            throw new VcaException("订单不存在");
        }
        if (!Objects.equals(storeOrder.getUid(),info.getUid())) {
            throw new VcaException("订单不存在");
        }

        //订单详情
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.getListByOrderNo(storeOrder.getOrderId());


        if (!storeOrder.getPaid()) {
            throw new VcaException("未支付");
        }
        if (!storeOrder.getStatus().equals(0)){
            throw new VcaException("订单状态错误"+storeOrder.getStatus());
        }
        if (!storeOrder.getRefundStatus().equals(0)){
            throw new VcaException("订单退款状态错误"+storeOrder.getRefundStatus());
        }

        //退款
        List<UmsPayRefundVo> refundList = new ArrayList();
        //如果实际支付金额为0则只变更状态 不需要退款
        if (storeOrder.getPayPrice().compareTo(BigDecimal.ZERO) <= 0){
            storeOrder.setRefundStatus(2);
            storeOrder.setRefundPrice(storeOrder.getPayPrice());
            storeOrder.setRefundApplicationTime(DateUtil.nowDateTime());
            storeOrder.setRefundReasonWap("未发货取消订单");
            //更新集合
            ArrayList<StoreOrderInfo> storeOrderInfos = new ArrayList<>();
            for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
                storeOrderInfo.setRefundStatus(2);
                storeOrderInfo.setRefundPrice(storeOrderInfo.getPayPrice());
                storeOrderInfos.add(storeOrderInfo);
            }

            Boolean execute = transactionTemplate.execute(e -> {
                storeOrderService.updateById(storeOrder);
                storeOrderInfoService.updateBatchById(storeOrderInfos);
                storeOrderStatusService.createLog(storeOrder.getId(), "productCancel", 1,"商品订单取消！");
                return Boolean.TRUE;
            });
            if (execute){
                return true;
            }else {
                throw new VcaException("订单取消失败！");
            }
        }else {
            for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
                UmsPayRefundVo vo = new UmsPayRefundVo();
                vo.setAmount(storeOrderInfo.getPayPrice());
                vo.setMerOrderNo(storeOrderInfo.getMerOrderNo());
                refundList.add(vo);
            }
            Boolean refund = umsPayService.refund(refundList);
            if (refund) {
                redisUtil.lPush(TaskConstants.PRODUCT_ORDER_CANCEL, storeOrder.getId());
//            orderConsentRefund(storeOrder, storeOrderInfos);//消息通知
                return true;
            }{
                throw new VcaException("订单取消失败");
            }
        }
    }

    /**
     * 订单退款申请
     *
     * @param request OrderRefundApplyRequest 退款参数
     */
    @Override
    public Boolean refundApply(String language,OrderRefundApplyRequest request) {
        User info = userService.getInfo();
        StoreOrder storeOrder = storeOrderService.getByOrderId(request.getOrderNo());
        if (ObjectUtil.isEmpty(storeOrder)){
            throw new VcaException("订单不存在");
        }
        if (!Objects.equals(storeOrder.getUid(),info.getUid())){
            throw new VcaException("订单不存在");
        }

        //是否已过申请售后时间
        Date afterSalesDeadline = storeOrder.getAfterSalesDeadline();
        if (ObjectUtil.isNull(afterSalesDeadline)){
            throw new VcaException("售后截止时间为空");
        }



        if (storeOrder.getRefundStatus() > 0) {
            if("en".equals(language)){
                throw new VcaException("Already Applied, No Repeats!");
            }else{
                throw new VcaException("已申请过，不可重复申请！");
            }
        }


        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().in(StoreOrderInfo::getMerOrderNo, request.getMerOrderNos()));

        VcaProduct vcaProduct = vcaProductService.getById(storeOrderInfos.get(0).getProductId());
        if (new Date().getTime()>afterSalesDeadline.getTime() && !vcaProduct.getCid().equals(750)){
            if("en".equals(language)){
                throw new VcaException("Order Past After-sales Period");
            }else{
                throw new VcaException("订单已超售后有效期");
            }
        }
        if (ObjectUtil.isEmpty(vcaProduct)){
            throw new VcaException("商品信息为空");
        }
        for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
            if (storeOrderInfo.getRefundStatus() == 1) {
                if("en".equals(language)){
                    throw new VcaException("Already Applied, No Repeats!");
                }else{
                    throw new VcaException("已申请过，不可重复申请！");
                }
            }



            if (vcaProduct.getCid().equals(750)){
                //礼品卡集合
                List<UserCard> userCardList = userCardService.list(new LambdaQueryWrapper<UserCard>().eq(UserCard::getOrderId, storeOrderInfo.getMerOrderNo()));

                for (UserCard userCard : userCardList) {
                    if (!userCard.getUid().equals(storeOrder.getUid())){
                        if("en".equals(language)){
                            throw new VcaException("Gift Certificate Gifted & Claimed, No Refunds!");
                        }else{
                            throw new VcaException("该订单礼品卡已赠送并已领取，不可申请退款！");
                        }
                    }

                    if (!userCard.getStutus().equals(0)){
                        if("en".equals(language)){
                            throw new VcaException("Gift Certificate Used/Expired, No Refunds!");
                        }else{
                            throw new VcaException("该礼品卡已使用或已过期，不可申请退款！");
                        }

                    }
                }
            }


        }
        //如果礼品卡订单未超过售后时间则直接退款
        if (new Date().getTime()<afterSalesDeadline.getTime()&&vcaProduct.getCid().equals(750)){
            LambdaUpdateWrapper<StoreOrder> storeOrderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            storeOrderLambdaUpdateWrapper.set(StoreOrder::getRefundReasonWap,request.getRefundReasonWap());
            storeOrderLambdaUpdateWrapper.eq(StoreOrder::getOrderId,request.getOrderNo());
            storeOrderService.update(storeOrderLambdaUpdateWrapper);
            return  storeOrderService.giftCardRefund(storeOrder, storeOrderInfos);
        }

        //课程讲座展览退款流程
//        if (!storeOrder.getType().equals(4)) {
//            //一年内是否退款
//            Integer userId = userService.getUserId();
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Calendar c = Calendar.getInstance();
//            c.setTime(new Date());
//            c.add(Calendar.YEAR, -1);
//            Date y = c.getTime();
//            String year = format.format(y);
//            LambdaQueryWrapper<StoreOrder> storeOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            storeOrderLambdaQueryWrapper.in(StoreOrder::getRefundStatus, 1, 2, 3);
//            storeOrderLambdaQueryWrapper.in(StoreOrder::getType, 0, 1, 2, 3);
//            storeOrderLambdaQueryWrapper.eq(StoreOrder::getPaid, 1);
//            storeOrderLambdaQueryWrapper.eq(StoreOrder::getUid, userId);
//            storeOrderLambdaQueryWrapper.gt(StoreOrder::getRefundReasonTime, y);
//            List<StoreOrder> list = storeOrderService.list(storeOrderLambdaQueryWrapper);
//
//
//            List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().in(StoreOrderInfo::getMerOrderNo, request.getMerOrderNos()).eq(StoreOrderInfo::getIsGet, 1).orderByAsc(StoreOrderInfo::getSchedulingDate, StoreOrderInfo::getSchedulingStartTime));
//            String time = storeOrderInfos.get(0).getSchedulingDate() + " " + storeOrderInfos.get(0).getSchedulingStartTime() + ":00";
//            //预约时间
//            Date date = null;
//            //当前时间
//            Date currentTime = null;
//            String cancelIime = "";
//            if (storeOrder.getType().equals(0) || storeOrder.getType().equals(1)) {
//                cancelIime = systemConfigService.getValueByKey("course_cancel_time");
//            } else if (storeOrder.getType().equals(2)) {
//                cancelIime = systemConfigService.getValueByKey("talk_cancel_time");
//            } else if (storeOrder.getType().equals(3)) {
//                cancelIime = systemConfigService.getValueByKey("exhibition_cancel_time");
//            }
//            try {
//                date = format.parse(time);
//                currentTime = format.parse(format.format(new Date()));
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            long dayM = 1000 * 24 * 60 * 60;
//            long hourM = 1000 * 60 * 60;
//            long differ = date.getTime() - currentTime.getTime();
//            long hour = differ % dayM / hourM + 24 * (differ / dayM); //预约时间减去当前时间毫秒数
//
//            if (list.size() > 100000) {
//                throw new VcaException("一年内有退款，不能申请！");
//            }
//            if (hour < Integer.parseInt(cancelIime)) {
//                throw new VcaException("已接近上课时间，不能申请！");
//            }
//            List<StoreOrderInfo> orderInfos = new ArrayList<>();
//            List<String> merOrderNos = new ArrayList<>();
//            //退款判断  如果不是后台赠送并且金额不为0 则调用退款接口并更新订单状态为退款中
//            for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
//                merOrderNos.add(storeOrderInfo.getMerOrderNo());
//            }
//            if (storeOrder.getUserType().equals(0) && storeOrder.getPayPrice().compareTo(BigDecimal.ZERO) > 0) {
//
//                //退款
//                List<UmsPayRefundVo> refundList = new ArrayList();
//                UmsPayRefundVo vo = new UmsPayRefundVo();
//                for (String merOrderNo : merOrderNos) {
//                    vo.setMerOrderNo(merOrderNo);
//                    refundList.add(vo);
//                }
//                refundList.get(0).setAmount(storeOrder.getPayPrice());
//                try {
//                    return umsPayService.refund(refundList);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    throw new VcaException("申请退款失败！");
//                }
////                //更新订单状态为退款中
////                for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
////                    storeOrderInfo.setRefundStatus(3);
////                    storeOrderInfo.setRefundReasonTime(DateUtil.nowDateTime());
////                    if (!storeOrderInfo.getType().equals(1)) { //如果为套课 则退款金额不赋值
////                        storeOrderInfo.setRefundPrice(storeOrder.getPayPrice());
////                    }
////                    orderInfos.add(storeOrderInfo);
////                }
////                storeOrder.setRefundStatus(3);
////                storeOrder.setRefundReasonTime(DateUtil.nowDateTime());
////                storeOrder.setRefundPrice(BigDecimal.ZERO);
//            } else {
//                //为后台赠送或金额为0 则直接修改订单状态为已退款 并把退款后续操作放进redis
//                for (StoreOrderInfo storeOrderInfo : storeOrderInfos) { //更新info表状态
//                    merOrderNos.add(storeOrderInfo.getMerOrderNo());
//                    storeOrderInfo.setRefundStatus(2);
//                    storeOrderInfo.setRefundReasonTime(DateUtil.nowDateTime());
////                    storeOrderInfo.setRefundPrice(storeOrder.getPayPrice());
//                    orderInfos.add(storeOrderInfo);
//                }
//                //更新order表状态
//                storeOrder.setRefundStatus(2);
//                storeOrder.setRefundApplicationTime(DateUtil.nowDateTime());
//                storeOrder.setRefundPrice(storeOrder.getPayPrice());
//
//                // 退款task
//                redisUtil.lPush(Constants.ORDER_TASK_REDIS_KEY_AFTER_REFUND_BY_USER, storeOrder.getId());//todo
//            }
//            Boolean execute = transactionTemplate.execute(e -> {
//                storeOrderInfoService.updateBatchById(orderInfos);
//                storeOrderService.updateById(storeOrder);
//                storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_LOG_REFUND_APPLY, 1,"用户申请退款原因：" + request.getExplain());
//                return Boolean.TRUE;
//            });
//            if (!execute) {
//                storeOrderStatusService.saveRefund(storeOrder.getId(), storeOrder.getPayPrice(), "失败");
//                throw new VcaException("订单更新失败");
//            }
//            return execute;
//        }
        //商品退款流程
        Boolean execute1 = transactionTemplate.execute(e -> {

            ArrayList<UserCard> userCards = new ArrayList<>();
            List<StoreOrderInfo> orderInfoList = new ArrayList<>();

            for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
                storeOrderInfo.setRefundStatus(1);
                storeOrderInfo.setRefundReasonTime(DateUtil.nowDateTime());
                storeOrderInfo.setRefundPrice(BigDecimal.ZERO);
                orderInfoList.add(storeOrderInfo);
                if (vcaProduct.getCid().equals(750)){
                    //礼品卡集合
                    List<UserCard> userCardList = userCardService.list(new LambdaQueryWrapper<UserCard>().eq(UserCard::getOrderId, storeOrderInfo.getMerOrderNo()));
                    for (UserCard userCard : userCardList) {
                        userCard.setStutus(2);
                        userCards.add(userCard);
                    }
                }

            }
            storeOrderInfoService.updateBatchById(orderInfoList);
            if (CollUtil.isNotEmpty(userCards)){
                userCardService.updateBatchById(userCards);
            }
            //判断所有商品退款状态是否一致 一致更新主订单状态
//            if (getOrderInfoStatusIsAll(1, request.getMerOrderNos())) {
            storeOrder.setRefundStatus(1);
//            }
            storeOrder.setRefundApplicationTime(DateUtil.nowDateTime());
            storeOrder.setApplyRefundType("退货退款");
            storeOrder.setRefundReasonWap(request.getRefundReasonWap());
            storeOrder.setRefundReasonWapExplain(request.getExplain());
//        storeOrder.setRefundReasonWapImg(systemAttachmentService.clearPrefix(request.getReasonImage()));
            storeOrder.setRefundPrice(BigDecimal.ZERO);
            storeOrderService.updateById(storeOrder);
            storeOrderStatusService.createLog(storeOrder.getId(), Constants.ORDER_LOG_REFUND_APPLY, 1,"用户申请退款原因：" + request.getRefundReasonWap());
            return Boolean.TRUE;
        });
        if (!execute1) {
            if("en".equals(language)){
                throw new VcaException("Refund Request Failed");
            }else{
                throw new VcaException("申请退款失败");
            }
        }
        if (execute1) {
            // 发送用户退款管理员提醒短信
//            SystemNotification notification = systemNotificationService.getByMark(NotifyConstants.APPLY_ORDER_REFUND_ADMIN_MARK);
//            if (notification.getIsSms().equals(1)) {
//                // 查询可已发送短信的管理员
//                List<SystemAdmin> systemAdminList = systemAdminService.findIsSmsList();
//                if (CollUtil.isNotEmpty(systemAdminList)) {
//                    SmsTemplate smsTemplate = smsTemplateService.getDetail(notification.getSmsId());
//                    Integer tempId = Integer.valueOf(smsTemplate.getTempId());
//                    // 发送短信
//                    systemAdminList.forEach(admin -> {
//                        smsService.sendOrderRefundApplyNotice(admin.getPhone(), storeOrder.getOrderId(), admin.getRealName(), tempId);
//                    });
//                }
//            }
        }
        if (!execute1) {
            if("en".equals(language)) {
                throw new VcaException("Refund Request Failed");
            }else{
                throw new VcaException("申请退款失败");
            }
        }
        return execute1;
    }

//    public static void main(String[] args) {
//
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
//        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.SECOND, 0);
//        calendar.set(Calendar.MILLISECOND, 0);
//        Date calendarTime = calendar.getTime();
//        Date addDays = DateUtils.addDays(calendarTime, 7);
//        System.out.println(calendarTime + "  :  " +addDays);
//    }


    /**
     * 售后详情
     *
     * @param orderNo
     * @return
     */
    @Override
    public AfterSaleInfoResponse refundInfo(String language,String orderNo) {
        User info = userService.getInfo();
        AfterSaleInfoResponse afterSaleInfoResponse = new AfterSaleInfoResponse();

        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);

        if (ObjectUtil.isNull(storeOrder)){
            throw new VcaException("订单不存在");
        }

        if (!Objects.equals(storeOrder.getUid(),info.getUid())){
            throw new VcaException("订单不存在");
        }
        if (storeOrder.getRefundStatus().equals(0)){
            if("en".equals(language)){
                throw new VcaException("No After-sales Applied");
            }else{
                throw new VcaException("该订单未申请售后");
            }
        }
        afterSaleInfoResponse.setOrderNo(orderNo);
        BeanUtils.copyProperties(storeOrder, afterSaleInfoResponse);
        afterSaleInfoResponse.setWaybill(storeOrder.getReturnWaybillNo());

        StringBuilder stringBuilder = new StringBuilder();
        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.getListByOrderNo(orderNo);

        ArrayList<BigDecimal> bigDecimals = new ArrayList<>();
        for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
            if (storeOrderInfo.getRefundStatus().equals(1) || storeOrderInfo.getRefundStatus().equals(4)
                    || storeOrderInfo.getRefundStatus().equals(5) || storeOrderInfo.getRefundStatus().equals(6)){
                bigDecimals.add(storeOrderInfo.getPayPrice());
            }
            if (!storeOrderInfo.getRefundStatus().equals(0)){
                if("en".equals(language)){
                    stringBuilder.append(storeOrderInfo.getNameEn()).append("，");
                }else{
                    stringBuilder.append(storeOrderInfo.getName()).append("，");
                }

            }
        }
        //如果退款状态不为已退款或退款中 则退款金额取实际支付金额
        if (!storeOrder.getRefundStatus().equals(2) || !storeOrder.getRefundStatus().equals(3)){
            if (CollUtil.isNotEmpty(bigDecimals)){
                BigDecimal bigDecimal = bigDecimals.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
                afterSaleInfoResponse.setRefundPrice(bigDecimal);
            }
        }else {
            afterSaleInfoResponse.setRefundPrice(storeOrder.getRefundPrice());
        }

        //退款明细
        afterSaleInfoResponse.setRefundDetails(stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1));

        //退货的收货信息
        afterSaleInfoResponse.setConsigneeName(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_NAME));
        afterSaleInfoResponse.setConsigneePhone(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_TEL));
        afterSaleInfoResponse.setConsigneeAddress(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_ADDRESS));

//        //上门取件时间范围
//        String valueByKey = systemConfigService.getValueByKey(Constants.PICK_UP_TIME);
//        afterSaleInfoResponse.setPickUpStartTimeRange(valueByKey.substring(0,5));
//        afterSaleInfoResponse.setPickUpEndTimeRange(valueByKey.substring(6,11));

        //寄出倒计时
        if (storeOrder.getRefundStatus().equals(4)) {
            String returnSendTime = systemConfigService.getValueByKey(Constants.RETURN_SEND_TIME);

            Date agreedReturnTime = storeOrder.getAgreedReturnTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(agreedReturnTime);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date calendarTime = calendar.getTime();
            Date addDays = DateUtils.addDays(calendarTime, Integer.parseInt(returnSendTime)+1);
            afterSaleInfoResponse.setReturnEndTime(addDays);
            afterSaleInfoResponse.setDeliveryCountdown(addDays.getTime());
        }

        //退货物流
        if (StringUtils.isNotBlank(storeOrder.getReturnWaybillNo())) {
            ResponseCancel orderRouting = sfService.getOrderRouting("",storeOrder.getOrderId(), 2);
            if (ObjectUtil.isNotEmpty(orderRouting) && ObjectUtil.isNotEmpty(orderRouting.getMsgData())){
                Map<String, Object> innerMap = orderRouting.getMsgData().getInnerMap();
                JSONArray jsonArray = (JSONArray) innerMap.get("routeResps");
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                JSONArray routes = (JSONArray) jsonObject.get("routes");
                if (ObjectUtil.isNotEmpty(routes)){
                    List<Routes> routesList = JSONObject.parseArray(routes.toJSONString(), Routes.class);
                    List<Routes> collect = routesList.stream().sorted(Comparator.comparing(Routes::getAcceptTime).reversed()).collect(Collectors.toList());
                    afterSaleInfoResponse.setRoutesList(collect.get(0));
                }else{
                    Routes route = new Routes();
                    route.setRemark("未揽收或寄件时间超过3个月！");
                    afterSaleInfoResponse.setRoutesList(route);
                }
            }
        }

        //是否已过申请售后时间
        Date afterSalesDeadline = storeOrder.getAfterSalesDeadline();
        if (ObjectUtil.isNotNull(afterSalesDeadline)){
            if (new Date().getTime()<afterSalesDeadline.getTime()){
                afterSaleInfoResponse.setIsAfterSalesTime(false);
            }else {
                afterSaleInfoResponse.setIsAfterSalesTime(true);
            }
        }
        //售后历史
        List<StoreOrderStatus> storeOrderStatusList = storeOrderStatusService.list(new LambdaQueryWrapper<StoreOrderStatus>().eq(StoreOrderStatus::getType, 1).eq(StoreOrderStatus::getOid, storeOrder.getId()).orderByDesc(StoreOrderStatus::getCreateTime));
        afterSaleInfoResponse.setStoreOrderStatuseList(storeOrderStatusList);
        return afterSaleInfoResponse;
    }

    /**
     * 退货下单
     *
     * @param request
     * @return
     */
    @Override
    public CommonResult refundAnOrder(RefundAnOrderRequest request) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;
        try {
            date = format.parse(request.getPickUpDate() + " "+request.getPickUpStartTime() + ":00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        User info = userService.getInfo();

        StoreOrder storeOrder = storeOrderService.getByOrderId(request.getOrderNo());

        if (ObjectUtil.isEmpty(storeOrder)) {
            throw new VcaException("该订单不存在！");
        }

        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, request.getOrderNo()).eq(StoreOrderInfo::getRefundStatus, 4));

        if (!Objects.equals(storeOrder.getUid(),info.getUid())) {
            throw new VcaException("该订单不存在！");
        }

        if (!storeOrder.getRefundStatus().equals(4)) {
            throw new VcaException("该订单状态不匹配 无法下单！");
        }

        String refundOrderNo = "";
        if (StringUtils.isBlank(storeOrder.getReturnOrderNo())){
            refundOrderNo = VcaUtil.getOrderNo("T");
        }else {
            refundOrderNo = storeOrder.getReturnOrderNo();
        }


        StringBuilder ProductName = new StringBuilder();
        for (int i = 0; i < storeOrderInfos.size(); i++) {
            ProductName.append(storeOrderInfos.get(i).getName()).append(" ");
        }
        //顺丰下单参数实体
        MsgData md = new MsgData();
        //托寄物信息
        List<CargoDetail> cargoDetailList = new ArrayList<>();
        CargoDetail cargoDetail = new CargoDetail();
        cargoDetail.setName(ProductName.toString());
        cargoDetailList.add(cargoDetail);
        //收寄方信息
        ArrayList<ContactInfo> contactInfos = new ArrayList<>();
        //收件人信息
        ContactInfo addresseeInfo = new ContactInfo();
        //寄件人信息
        ContactInfo senderInfo = new ContactInfo();

        addresseeInfo.setContactType(2);
        addresseeInfo.setContact(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_NAME));
        addresseeInfo.setMobile(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_TEL));
        addresseeInfo.setTel(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_TEL));
        addresseeInfo.setCountry("CN");
        addresseeInfo.setAddress(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_ADDRESS));
        contactInfos.add(addresseeInfo);

        //寄件方信息

        senderInfo.setContactType(1);
        senderInfo.setContact(request.getReturnUserName());
        senderInfo.setMobile(request.getReturnUserPhone());
        senderInfo.setTel(request.getReturnUserPhone());
        senderInfo.setCountry("CN");
        senderInfo.setAddress(request.getReturnUserAddress());
        contactInfos.add(senderInfo);

        md.setLanguage("zh-CN");
        md.setOrderId(refundOrderNo);
        md.setCargoDetails(cargoDetailList);
        md.setContactInfoList(contactInfos);
        md.setMonthlyCard(systemConfigService.getValueByKey(Constants.MONTHLY_CARD));
        md.setPayMethod(2);
        md.setExpressTypeId(1);
        md.setParcelQty(1);
        md.setIsDocall(1);
        md.setIsReturnRoutelabel(1);
        md.setSendStartTm(date);

        logger.info("退货下单请求参数："+md);
        //调用第三方 返回数据
        ResponseCancel responseCreate = sfUtil.fopReceLtlCreateOrder(md,disable);
        //判断第三方是否成功  成功则拿到运单号 失败返回
        if (responseCreate.getSuccess()) {
            JSONObject msgData = responseCreate.getMsgData();
            Map<String, Object> innerMap = msgData.getInnerMap();
            JSONArray jsonArray = (JSONArray) innerMap.get("waybillNoInfoList");
            List<WaybillNoInfo> statusList = JSONObject.parseArray(jsonArray.toJSONString(), WaybillNoInfo.class);
            String masterWaybillNo = "";
            for (int i = 0; i < statusList.size(); i++) {
                if (statusList.get(i).getWaybillType().equals(1)) {
                    masterWaybillNo = statusList.get(i).getWaybillNo();
                }
            }
            Express express = expressService.getByCode(Constants.SF);
            //更新数据
            storeOrder.setReturnWaybillNo(masterWaybillNo);
            storeOrder.setPickUpDate(request.getPickUpDate());
            storeOrder.setPickUpStartTime(request.getPickUpStartTime());
            storeOrder.setPickUpEndTime(request.getPickUpEndTime());
            storeOrder.setReturnUserName(request.getReturnUserName());
            storeOrder.setReturnUserPhone(request.getReturnUserPhone());
            storeOrder.setReturnUserAddress(request.getReturnUserAddress());
            storeOrder.setReturnOrderNo(refundOrderNo);
            storeOrder.setReturnDeliveryTime(new Date());
            storeOrder.setReturnSfStatus(1);


//            String message = Constants.ORDER_LOG_MESSAGE_EXPRESS.replace("{deliveryName}", express.getName()).replace("{deliveryCode}", storeOrder.getReturnWaybillNo());

            Boolean execute = transactionTemplate.execute(i -> {
                storeOrderService.updateById(storeOrder);
                storeOrderInfoService.updateBatchById(storeOrderInfos);
                //订单记录增加
                storeOrderStatusService.createLog(storeOrder.getId(),"refundAnOrder",1, "退货下单成功,快递公司："+express.getName()+",运单号："+storeOrder.getReturnWaybillNo());
                return Boolean.TRUE;
            });
            if (!execute) throw new VcaException("已发货,更新订单状态失败！");
            return CommonResult.success(responseCreate.getSuccess());
        }
        return CommonResult.failed(responseCreate.getErrorMsg());
    }

    /**
     * 退货下单取消
     * @param orderNo
     * @return
     */
    @Override
    public CommonResult refundAnOrderCancel(String orderNo) {


        //订单校验

        User info = userService.getInfo();
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);


        if (ObjectUtil.isNull(storeOrder)) {
            throw new VcaException("该订单不存在！");
        }
        if (!Objects.equals(storeOrder.getUid(),info.getUid())){
            throw new VcaException("该订单不存在！");
        }
        if (storeOrder.getIsDel()) {
            throw new VcaException("订单已取消");
        }

        if (StringUtils.isBlank(storeOrder.getReturnWaybillNo())) {
            throw new VcaException("该订单退货未下单");
        }
        if (storeOrder.getRefundStatus().equals(5) || storeOrder.getRefundStatus().equals(2) || storeOrder.getRefundStatus().equals(6)){
            throw new VcaException("包裹已寄出");
        }


        //取消订单参数
        MsgDataUpdate msgDataUpdate = new MsgDataUpdate();
        msgDataUpdate.setDealType(2);
        msgDataUpdate.setLanguage("zh-CN");
        msgDataUpdate.setOrderId(storeOrder.getReturnOrderNo());
        ResponseCancel responseCancel = sfUtil.fopReceLtlCancelOrder(msgDataUpdate,disable);
        if (responseCancel.getSuccess()) {
            LambdaUpdateWrapper<StoreOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(StoreOrder::getReturnOrderNo,null);
            lambdaUpdateWrapper.set(StoreOrder::getReturnWaybillNo,null);
            lambdaUpdateWrapper.set(StoreOrder::getPickUpDate,null);
            lambdaUpdateWrapper.set(StoreOrder::getPickUpStartTime,null);
            lambdaUpdateWrapper.set(StoreOrder::getPickUpEndTime,null);
            lambdaUpdateWrapper.set(StoreOrder::getReturnUserName,null);
            lambdaUpdateWrapper.set(StoreOrder::getReturnUserPhone,null);
            lambdaUpdateWrapper.set(StoreOrder::getReturnUserAddress,null);
            lambdaUpdateWrapper.set(StoreOrder::getReturnSfStatus,2);
            lambdaUpdateWrapper.eq(StoreOrder::getId,storeOrder.getId());
            Boolean execute = transactionTemplate.execute(i -> {
                storeOrderService.update(lambdaUpdateWrapper);
                storeOrderStatusService.createLog(storeOrder.getId(), "refundAnOrderCel",1, "退货下单已取消");
                return Boolean.TRUE;
            });
            if (!execute) throw new VcaException("退货订单已取消,更新订单状态失败！");
            return CommonResult.success(responseCancel.getSuccess());
        }

        return CommonResult.failed(responseCancel.getErrorMsg());
    }

    /**
     * 退款退货信息修改
     * @param request
     * @return
     */
    @Override
    public CommonResult refundUpdate(RefundAnOrderRequest request) {

        StoreOrder storeOrder = storeOrderService.getByOrderId(request.getOrderNo());
        if (ObjectUtil.isEmpty(storeOrder)){
            throw new VcaException("该订单不存在！");
        }

        if (!Objects.equals(storeOrder.getUid(),userService.getUserId())){
            throw new VcaException("该订单不存在！");
        }

        if (storeOrder.getRefundStatus().equals(5) || storeOrder.getRefundStatus().equals(2) || storeOrder.getRefundStatus().equals(6)){
            throw new VcaException("包裹已寄出，无法修改！");
        }
        //取消订单参数
        MsgDataUpdate msgDataUpdate = new MsgDataUpdate();
        msgDataUpdate.setDealType(2);
        msgDataUpdate.setLanguage("zh-CN");
        msgDataUpdate.setOrderId(storeOrder.getReturnOrderNo());
        ResponseCancel responseCancel = sfUtil.fopReceLtlCancelOrder(msgDataUpdate,disable);

        if (responseCancel.getSuccess()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date = null;
            try {
                date = format.parse(request.getPickUpDate() +" " +request.getPickUpStartTime() + ":00");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, request.getOrderNo()).eq(StoreOrderInfo::getRefundStatus, 4));

            if (!storeOrder.getRefundStatus().equals(4)) {
                throw new VcaException("该订单状态不匹配 无法下单！");
            }

            String refundOrderNo = VcaUtil.getOrderNo("T");

            StringBuilder ProductName = new StringBuilder();
            for (int i = 0; i < storeOrderInfos.size(); i++) {
                ProductName.append(storeOrderInfos.get(i).getName()).append(" ");
            }
            //顺丰下单参数实体
            MsgData md = new MsgData();
            //托寄物信息
            List<CargoDetail> cargoDetailList = new ArrayList<>();
            CargoDetail cargoDetail = new CargoDetail();
            cargoDetail.setName(ProductName.toString());
            cargoDetailList.add(cargoDetail);
            //收寄方信息
            ArrayList<ContactInfo> contactInfos = new ArrayList<>();
            //收件人信息
            ContactInfo addresseeInfo = new ContactInfo();
            //寄件人信息
            ContactInfo senderInfo = new ContactInfo();

            addresseeInfo.setContactType(2);
            addresseeInfo.setContact(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_NAME));
            addresseeInfo.setMobile(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_TEL));
            addresseeInfo.setTel(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_TEL));
            addresseeInfo.setCountry("CN");
            addresseeInfo.setAddress(systemConfigService.getValueByKey(Constants.CONFIG_EXPORT_TO_ADDRESS));
            contactInfos.add(addresseeInfo);

            //寄件方信息

            senderInfo.setContactType(1);
            senderInfo.setContact(request.getReturnUserName());
            senderInfo.setMobile(request.getReturnUserPhone());
            senderInfo.setTel(request.getReturnUserPhone());
            senderInfo.setCountry("CN");
            senderInfo.setAddress(request.getReturnUserAddress());
            contactInfos.add(senderInfo);

            md.setLanguage("zh-CN");
            md.setOrderId(refundOrderNo);
            md.setCargoDetails(cargoDetailList);
            md.setContactInfoList(contactInfos);
            md.setMonthlyCard(systemConfigService.getValueByKey(Constants.MONTHLY_CARD));
            md.setExpressTypeId(1);
            md.setParcelQty(1);
            md.setIsReturnRoutelabel(1);
            md.setSendStartTm(date);

            //调用第三方 返回数据
            ResponseCancel responseCreate = sfUtil.fopReceLtlCreateOrder(md,disable);
            //判断第三方是否成功  成功则拿到运单号 失败返回
            if (responseCreate.getSuccess()) {
                JSONObject msgData = responseCreate.getMsgData();
                Map<String, Object> innerMap = msgData.getInnerMap();
                JSONArray jsonArray = (JSONArray) innerMap.get("waybillNoInfoList");
                List<WaybillNoInfo> statusList = JSONObject.parseArray(jsonArray.toJSONString(), WaybillNoInfo.class);
                String masterWaybillNo = "";
                for (int i = 0; i < statusList.size(); i++) {
                    if (statusList.get(i).getWaybillType().equals(1)) {
                        masterWaybillNo = statusList.get(i).getWaybillNo();
                    }
                }
                Express express = expressService.getByCode(Constants.SF);
                //更新数据
                storeOrder.setReturnWaybillNo(masterWaybillNo);
                storeOrder.setPickUpDate(request.getPickUpDate());
                storeOrder.setPickUpStartTime(request.getPickUpStartTime());
                storeOrder.setPickUpEndTime(request.getPickUpEndTime());
                storeOrder.setReturnUserName(request.getReturnUserName());
                storeOrder.setReturnUserPhone(request.getReturnUserPhone());
                storeOrder.setReturnUserAddress(request.getReturnUserAddress());
                storeOrder.setReturnOrderNo(refundOrderNo);
                storeOrder.setReturnSfStatus(1);

//                String message = Constants.ORDER_LOG_MESSAGE_EXPRESS.replace("{deliveryName}", express.getName()).replace("{deliveryCode}", storeOrder.getReturnWaybillNo());

                Boolean execute = transactionTemplate.execute(i -> {
                    storeOrderService.updateById(storeOrder);
                    storeOrderInfoService.updateBatchById(storeOrderInfos);
                    //订单记录增加
                    storeOrderStatusService.createLog(storeOrder.getId(), "ReturnOrderUptade",1, "修改寄件信息：快递公司："+express.getName()+",运单号："+storeOrder.getReturnWaybillNo());
                    return Boolean.TRUE;
                });
                if (!execute) {
                    throw new VcaException("下单成功，更新订单信息失败！");
                }
                return CommonResult.success(responseCreate.getSuccess());
            }
            return CommonResult.failed(responseCreate.getErrorMsg());
        }
        return CommonResult.failed(responseCancel.getErrorMsg());
    }

    /**
     * 撤销申请
     * @param orderNo
     * @return
     */
    @Override
    public CommonResult refundRevocation(String orderNo) {

        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);

        if (ObjectUtil.isNull(storeOrder)) {
            throw new VcaException("该订单不存在！");
        }
        if (!Objects.equals(storeOrder.getUid(),userService.getUserId())){
            throw new VcaException("该订单不存在！");
        }

        if (storeOrder.getIsDel()) throw new VcaException("订单已取消");

        if (storeOrder.getRefundStatus().equals(5)){
            throw new VcaException("包裹已寄出，无法撤销！");
        }

        if (storeOrder.getRefundStatus().equals(6)){
            throw new VcaException("退款已取消！");
        }
        if (storeOrder.getRefundStatus().equals(2)){
            throw new VcaException("已退款！");
        }


        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, orderNo).in(StoreOrderInfo::getRefundStatus, 1,4));

        //商品信息 用于判断是否为礼品卡订单
        VcaProduct vcaProduct = vcaProductService.getById(storeOrderInfos.get(0).getProductId());

        if(ObjectUtil.isEmpty(vcaProduct)) {
            throw new VcaException("商品信息为空");
        }

//        //如果已发货 则拦截寄回
//        if (storeOrder.getRefundStatus().equals(5)) {
//
//            //取消订单参数
//            MsgDataIntercept msgDataIntercept = new MsgDataIntercept();
//            msgDataIntercept.setWaybillNo(storeOrder.getMasterWaybillNo());
//            msgDataIntercept.setServiceCode("2");
//            msgDataIntercept.setRole("1");
//            msgDataIntercept.setPayMode("4");
//            msgDataIntercept.setMonthlyCardNo(systemConfigService.getValueByKey("monthly_card"));
//            ResponseCancel responseCancel = sfUtil.fopInterceptOrder(msgDataIntercept,disable);
//            if (responseCancel.getSuccess()) {
//                if ((Boolean) responseCancel.getMsgData().get("success")) {
//                    storeOrder.setReturnOrderNo(null);
//                    storeOrder.setPickUpDate(null);
//                    storeOrder.setPickUpStartTime(null);
//                    storeOrder.setPickUpEndTime(null);
//                    storeOrder.setReturnUserName(null);
//                    storeOrder.setReturnUserPhone(null);
//                    storeOrder.setReturnUserAddress(null);
//                    storeOrder.setReturnWaybillNo(null);
//                    storeOrder.setRefundPrice(null);
//                    storeOrder.setRefundReasonWap(null);
//                    storeOrder.setApplyRefundType(null);
//                    storeOrder.setLogisticsType(4);
//                    storeOrder.setRefundStatus(6);
//
//
//                    ArrayList<StoreOrderInfo> orderInfoArrayList = new ArrayList<>();
//                    for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
//                        storeOrderInfo.setRefundStatus(6);
//                        orderInfoArrayList.add(storeOrderInfo);
//                    }
//                    Boolean execute = transactionTemplate.execute(i -> {
//                        storeOrderService.updateById(storeOrder);
//                        storeOrderInfoService.updateBatchById(orderInfoArrayList);
//                        //订单记录增加
//                        storeOrderStatusService.createLog(storeOrder.getId(), "refundRevocation", 1,"退款退货已取消");
//                        return Boolean.TRUE;
//                    });
//                    if (!execute) {
//                        throw new VcaException("撤销退款成功 但订单信息更新失败");
//                    }
//                    return CommonResult.success(responseCancel.getSuccess());
//                } else {
//                    storeOrder.setLogisticsType(5);
//                    storeOrderService.updateById(storeOrder);
//                    return CommonResult.failed(responseCancel.getMsgData().get("errorMsg").toString());
//                }
//            } else {
//                storeOrder.setLogisticsType(5);
//                storeOrderService.updateById(storeOrder);
//                return CommonResult.failed(responseCancel.getErrorMsg());
//            }
//        } else

        if (storeOrder.getRefundStatus().equals(4) && StringUtils.isNotEmpty(storeOrder.getReturnWaybillNo())) {//如果已下单待上门取件 则取消顺丰订单
            //取消订单参数
            MsgDataUpdate msgDataUpdate = new MsgDataUpdate();
            msgDataUpdate.setDealType(2);
            msgDataUpdate.setLanguage("zh-CN");
            msgDataUpdate.setOrderId(storeOrder.getReturnOrderNo());
            ResponseCancel responseCancel = sfUtil.fopReceLtlCancelOrder(msgDataUpdate,disable);
            if (responseCancel.getSuccess()) {
                LambdaUpdateWrapper<StoreOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(StoreOrder::getReturnOrderNo,null);
                lambdaUpdateWrapper.set(StoreOrder::getReturnWaybillNo,null);
                lambdaUpdateWrapper.set(StoreOrder::getPickUpDate,null);
                lambdaUpdateWrapper.set(StoreOrder::getPickUpStartTime,null);
                lambdaUpdateWrapper.set(StoreOrder::getPickUpEndTime,null);
                lambdaUpdateWrapper.set(StoreOrder::getReturnUserName,null);
                lambdaUpdateWrapper.set(StoreOrder::getReturnUserPhone,null);
                lambdaUpdateWrapper.set(StoreOrder::getReturnUserAddress,null);
                lambdaUpdateWrapper.set(StoreOrder::getReturnSfStatus,2);
                lambdaUpdateWrapper.set(StoreOrder::getRefundPrice,null);
                lambdaUpdateWrapper.set(StoreOrder::getRefundStatus,6);
                lambdaUpdateWrapper.eq(StoreOrder::getId,storeOrder.getId());

                ArrayList<StoreOrderInfo> orderInfoArrayList = new ArrayList<>();
                for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
                    storeOrderInfo.setRefundStatus(6);
                    orderInfoArrayList.add(storeOrderInfo);
                }
                Boolean execute = transactionTemplate.execute(i -> {
                    storeOrderService.update(lambdaUpdateWrapper);
                    storeOrderInfoService.updateBatchById(orderInfoArrayList);
                    //订单记录增加
                    storeOrderStatusService.createLog(storeOrder.getId(), "refundRevocation",1, "退款退货已撤销");
                    return Boolean.TRUE;
                });
                if (!execute) {
                    throw new VcaException("撤销退款成功 但订单信息更新失败");
                }
                return CommonResult.success(responseCancel.getSuccess());
            }
            return CommonResult.failed(responseCancel.getErrorMsg());
        } else if ((storeOrder.getRefundStatus().equals(4) && StringUtils.isEmpty(storeOrder.getReturnWaybillNo())) || storeOrder.getRefundStatus().equals(1)) {//如果已同意退货 未顺丰下单
            LambdaUpdateWrapper<StoreOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(StoreOrder::getRefundStatus,6);
            lambdaUpdateWrapper.eq(StoreOrder::getId,storeOrder.getId());

            ArrayList<StoreOrderInfo> orderInfoArrayList = new ArrayList<>();

            ArrayList<UserCard> userCards = new ArrayList<>();
            for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
                storeOrderInfo.setRefundStatus(6);
                orderInfoArrayList.add(storeOrderInfo);
                if (vcaProduct.getCid().equals(750)){
                    //礼品卡集合
                    List<UserCard> userCardList = userCardService.list(new LambdaQueryWrapper<UserCard>().eq(UserCard::getOrderId, storeOrderInfo.getMerOrderNo()));
                    for (UserCard userCard : userCardList) {
                        userCard.setStutus(0);
                        userCards.add(userCard);
                    }
                }
            }
            Boolean execute = transactionTemplate.execute(i -> {
                storeOrderService.update(lambdaUpdateWrapper);
                storeOrderInfoService.updateBatchById(orderInfoArrayList);
                if (CollUtil.isNotEmpty(userCards)){
                    userCardService.updateBatchById(userCards);
                }
                //订单记录增加
                storeOrderStatusService.createLog(storeOrder.getId(), "refundRevocation",1, "退款退货已撤销");
                return Boolean.TRUE;
            });
            if (!execute) {
                throw new VcaException("撤销退款成功 但订单信息更新失败");
            }
            return CommonResult.success();
        }
        return CommonResult.success();
    }


    /**
     * 订单列表
     *
     * @param type        订单类型:1=课程/讲座/展览  2=礼品卡/纪念品/出版物
     * @param pageRequest 分页
     * @return CommonPage<OrderDetailResponse>
     */
    @Override
    public CommonPage<OrderDetailResponse> list(String language,Integer type, PageParamRequest pageRequest) {
        Integer userId = userService.getUserIdException();

        List<StoreOrder> orderList = storeOrderService.getUserOrderList(userId, type, pageRequest);
        CommonPage<StoreOrder> storeOrderCommonPage = CommonPage.restPage(orderList);
        List<OrderDetailResponse> responseList = CollUtil.newArrayList();
        //订单号集合
        List<String> orderIds = orderList.stream().map(StoreOrder::getOrderId).collect(Collectors.toList());

        //订单详情map
        Map<String, List<StoreOrderInfo>> map = storeOrderInfoService.getMapInIds(orderIds);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (StoreOrder storeOrder : orderList) {
            OrderDetailResponse infoResponse = new OrderDetailResponse();
            BeanUtils.copyProperties(storeOrder, infoResponse);
            infoResponse.setOrderNo(storeOrder.getOrderId());
            //订单类型
            infoResponse.setOrderType(getOrderActivityType(language,storeOrder));
            //图片
            ArrayList<String> images = new ArrayList<>();
            if (ObjectUtil.isNull(map.get(storeOrder.getOrderId()))){
                if("en".equals(language)){
                    throw new VcaException("The order details were not found orderNo:" +storeOrder.getOrderId());
                }else{
                    throw new VcaException("该订单详情未找到 orderNo:" +storeOrder.getOrderId());
                }
            }

            // 订单详情对象列表
            List<StoreOrderInfo> storeOrderInfos = map.get(storeOrder.getOrderId());

            for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
                //System.out.println(storeOrderInfo+"================");
                //商品订单特殊处理
                if (infoResponse.getType().equals(4)) {
                    PreOrderCommonVo.PreOrderProductDetail preOrderProductDetail1 = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.PreOrderProductDetail.class);
                    images.add(preOrderProductDetail1.getImage());
                    infoResponse.setImages(images);
                    if("en".equals(language)){
                        infoResponse.setName(storeOrderInfo.getNameEn());
                    }else{
                        infoResponse.setName(storeOrderInfo.getName());
                    }
                } else {
                    if (storeOrderInfo.getType().equals(1) || storeOrderInfo.getType().equals(0)) {
                        Category category = getCategory(language,storeOrderInfo);
                        //System.out.println(category+"-----------");
                        infoResponse.setThemeColor(category.getLabelColor());
                        if("en".equals(language)){
                            infoResponse.setTagText(category.getNameEn());
                        }else{
                            infoResponse.setTagText(category.getName());
                        }
                    } else if (storeOrderInfo.getType().equals(2)) {
                        Talk talk = talkService.getOne(new LambdaQueryWrapper<Talk>().eq(Talk::getId, storeOrderInfo.getMainId()));
                        if (ObjectUtil.isNull(talk)) {
                            if("en".equals(language)){
                                throw new VcaException("The lecture does not exist");
                            }else{
                                throw new VcaException("该讲座不存在");
                            }

                        }
                        if("en".equals(language)){
                            infoResponse.setTagText(talk.getTalkType().equals(1) ? "In-person Talk" : "Online Talk");
                        }else{
                            infoResponse.setTagText(talk.getTalkType().equals(1) ? "线下讲座" : "线上讲座");
                        }

                        infoResponse.setThemeColor("#B4B19E");
                    } else if (storeOrderInfo.getType().equals(3)) {
                        if("en".equals(language)){
                            infoResponse.setTagText("Exhibition");
                        }else{
                            infoResponse.setTagText("展览");
                        }
                        infoResponse.setThemeColor("#8C734A");
                    }
                    PreOrderCommonVo.CourseInfoDetail courseInfoDetail = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.CourseInfoDetail.class);
                    if("en".equals(language)){
                        infoResponse.setName(courseInfoDetail.getNameEn());
                    }else{
                        infoResponse.setName(courseInfoDetail.getName());
                    }
                    images.add(courseInfoDetail.getCoverImage());

                    //套课时间特殊处理
                    if (storeOrderInfo.getType().equals(1)) {
                        if (StringUtils.isNotBlank(infoResponse.getDate())) {
                            String responseTime = infoResponse.getDate() + " " + infoResponse.getStartTime() + ":00";
                            String infoTime = storeOrderInfo.getSchedulingDate() + " " + storeOrderInfo.getSchedulingStartTime() + ":00";
                            //info时间
                            Date infoDate = null;
                            //当前时间
                            Date responseDate = null;
                            try {
                                responseDate = format.parse(responseTime);
                                infoDate = format.parse(infoTime);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            if (infoDate.getTime() < responseDate.getTime() || infoDate.getTime() == responseDate.getTime()) {
                                infoResponse.setDate(storeOrderInfo.getSchedulingDate());
                                infoResponse.setStartTime(storeOrderInfo.getSchedulingStartTime());
                                infoResponse.setEndTime(storeOrderInfo.getSchedulingEndTime());
                            }
                        } else {
                            infoResponse.setDate(storeOrderInfo.getSchedulingDate());
                            infoResponse.setStartTime(storeOrderInfo.getSchedulingStartTime());
                            infoResponse.setEndTime(storeOrderInfo.getSchedulingEndTime());
                        }
                    } else {
                        infoResponse.setDate(storeOrderInfo.getSchedulingDate());
                        infoResponse.setStartTime(storeOrderInfo.getSchedulingStartTime());
                        infoResponse.setEndTime(storeOrderInfo.getSchedulingEndTime());
                    }
                    infoResponse.setImages(images);
                }
            }
            // 订单状态
            infoResponse.setOrderStatus(getH5OrderStatus(language,storeOrder,storeOrderInfos));
            responseList.add(infoResponse);
        }
        CommonPage<OrderDetailResponse> detailPage = CommonPage.restPage(responseList);
        BeanUtils.copyProperties(storeOrderCommonPage, detailPage, "list");
        return detailPage;
    }

    public Category getCategory(String language,StoreOrderInfo storeOrderInfo){
        ArrayList<Long> ids = new ArrayList<>();
        if (storeOrderInfo.getType().equals(0)){
            ids.add(storeOrderInfo.getMainId());
            List<Course> courseAndDelete = courseService.getCourseAndDelete(ids);
//            Course course = courseService.getOne(new LambdaQueryWrapper<Course>().eq(Course::getId, storeOrderInfo.getMainId()));
            if (CollUtil.isEmpty(courseAndDelete)){
                if("en".equals(language)){
                    throw new VcaException("This order course does not exist");
                }else{
                    throw new VcaException("该订单课程不存在");
                }
            }
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getId, courseAndDelete.get(0).getCourseTypeId()));
            if (ObjectUtil.isNull(category)){
                if("en".equals(language)){
                    throw new VcaException("This category does not exist");
                }else{
                    throw new VcaException("该类别不存在");
                }
            }
            return category;
        }else if (storeOrderInfo.getType().equals(1)){
            ids.add(storeOrderInfo.getMainId());
//            CoursePackage coursePackage = coursePackageService.getOne(new LambdaQueryWrapper<CoursePackage>().eq(CoursePackage::getId, storeOrderInfo.getMainId()));
            List<CoursePackage> coursePackages = coursePackageService.getCoursePackagesAndDelete(ids);
            if (ObjectUtil.isNull(coursePackages)){
                if("en".equals(language)){
                    throw new VcaException("This order set does not exist");
                }else{
                    throw new VcaException("该订单套课不存在");
                }
            }
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getId, coursePackages.get(0).getCourseTypeId()));
            if (ObjectUtil.isNull(category)){
                if("en".equals(language)){
                    throw new VcaException("This category does not exist");
                }else{
                    throw new VcaException("该类别不存在");
                }
            }
            return category;
        }
        return new Category();
    }

    //是否全部退款
    public Integer isAllRefund(StoreOrder storeOrder,List<StoreOrderInfo> orderInfoArrayList){
        Integer refunded = 0;
        for (StoreOrderInfo storeOrderInfo : orderInfoArrayList) {
            if (storeOrderInfo.getRefundStatus().equals(2)){
                refunded = refunded + 1;
            }
        }

        if (storeOrder.getRefundStatus().equals(2)){
            if (storeOrder.getType().equals(1) || refunded.equals(orderInfoArrayList.size())){
                return 1;
            }else {
                return 2;
            }
        }else {
            return 3;
        }
    }

    //是否全部退款中
    public Integer isAllUnderRefund(StoreOrder storeOrder,List<StoreOrderInfo> orderInfoArrayList){
        Integer underRefund = 0;
        for (StoreOrderInfo storeOrderInfo : orderInfoArrayList) {
            if (storeOrderInfo.getRefundStatus().equals(1) || storeOrderInfo.getRefundStatus().equals(3) || storeOrderInfo.getRefundStatus().equals(4) || storeOrderInfo.getRefundStatus().equals(5)){
                underRefund = underRefund + 1;
            }
        }

        if (storeOrder.getRefundStatus().equals(1) || storeOrder.getRefundStatus().equals(3) || storeOrder.getRefundStatus().equals(4) || storeOrder.getRefundStatus().equals(5)){
            if (storeOrder.getType().equals(1) || underRefund.equals(orderInfoArrayList.size())){
                return 1;
            }else {
                return 2;
            }
        }else {
            return 3;
        }
    }

    //是否退款取消
    public Integer isAllRefundCancellation(StoreOrder storeOrder,List<StoreOrderInfo> orderInfoArrayList){
        Integer refundCancellation = 0;
        for (StoreOrderInfo storeOrderInfo : orderInfoArrayList) {
            if (storeOrderInfo.getRefundStatus().equals(6)){
                refundCancellation = refundCancellation + 1;
            }
        }

        if (storeOrder.getRefundStatus().equals(2)){
            if (refundCancellation.equals(orderInfoArrayList.size())){
                return 1;
            }else {
                return 2;
            }
        }else {
            return 3;
        }
    }

    /**
     * 获取订单类型
     *
     * @param storeOrder 订单类型
     * @return 订单类型 订单类型:0-课程订单 1=套课订单 2=讲座订单 3=展览订单 4=商品订单
     */
    private String getOrderActivityType(String language,StoreOrder storeOrder) {
        if (storeOrder.getType().equals(0)) {
            if("en".equals(language)){
                return "Course order";
            }else{
                return "课程订单";
            }

        }
        if (storeOrder.getType().equals(1)) {
            if("en".equals(language)){
                return "Transfer order";
            }else{
                return "套课订单";
            }
        }
        if (storeOrder.getType().equals(2)) {
            if("en".equals(language)){
                return "Lecture order";
            }else{
                return "讲座订单";
            }
        }
        if (storeOrder.getType().equals(3)) {
            if("en".equals(language)){
                return "Exhibition order";
            }else{
                return "展览订单";
            }
        }
        if (storeOrder.getType().equals(4)) {
            if("en".equals(language)){
                return "Merchandise order";
            }else{
                return "商品订单";
            }
        }
        return null;
    }

    /**
     * 获取H5订单状态
     *
     * @param storeOrder 订单对象
     */
    private String getH5OrderStatus(String language,StoreOrder storeOrder ,List<StoreOrderInfo> storeOrderInfos) {
        //是否全部退款
        Integer allRefund = isAllRefund(storeOrder, storeOrderInfos);
        //是否全部退款中
        Integer allUnderRefund = isAllUnderRefund(storeOrder, storeOrderInfos);
        //是否全部退款取消
        Integer allRefundCancellation = isAllRefundCancellation(storeOrder, storeOrderInfos);
        if (!storeOrder.getPaid() && !storeOrder.getIsDel() && !storeOrder.getIsSystemDel()) {
            if("en".equals(language)){
                return "Pending Payment";
            }else{
                return "待付款";
            }
        }
        if (storeOrder.getIsDel() || storeOrder.getIsSystemDel() || allRefund.equals(1)) {
            if("en".equals(language)){
                return "Cancelled";
            }else{
                return "已取消";
            }
        }

        if (storeOrder.getPaid() && (allUnderRefund.equals(1) && (storeOrder.getRefundStatus().equals(1) || storeOrder.getRefundStatus().equals(3)
                || storeOrder.getRefundStatus().equals(4) || storeOrder.getRefundStatus().equals(5)))) {
            if("en".equals(language)){
                return "Refund in Progress";
            }else{
                return "退款中";
            }
        }

        if (storeOrder.getPaid() && storeOrder.getStatus().equals(0)) {
            if("en".equals(language)){
                return "Paid";
            }else{
                return "已付款";
            }
        }
        if (storeOrder.getStatus().equals(1)) {
            if (storeOrder.getType().equals(4)) {
                if("en".equals(language)){
                    return "Pending Receipt";
                }else{
                    return "待收货";
                }
            } else {
                if("en".equals(language)){
                    return "Booked";
                }else{
                    return "已预约";
                }
            }
        }

        if (!storeOrder.getType().equals(4) && (storeOrder.getStatus().equals(2) || storeOrder.getStatus().equals(3))){
            if("en".equals(language)){
                return "Completed";
            }else{
                return "已完成";
            }
        }
        if (storeOrder.getType().equals(4) && (storeOrder.getStatus().equals(3) || allRefund.equals(2) || allUnderRefund.equals(2) || storeOrder.getRefundStatus().equals(6))) {
            if("en".equals(language)){
                return "Received";
            }else{
                return "已收货";
            }
        }

        return "";
    }

    /**
     * 订单详情
     *
     * @param orderNo 订单id
     */
    @Override
    public StoreOrderDetailInfoResponse detailOrder(String language,String orderNo) {
        User currentUser = userService.getInfoException();

        StoreOrderDetailInfoResponse storeOrderDetailResponse = new StoreOrderDetailInfoResponse();
        // 查询订单
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);
        if (ObjectUtil.isNull(storeOrder)) {
            if("en".equals(language)){
                throw new VcaException("订单不存在");
            }else{
                throw new VcaException("Order does not exist");
            }
        }
        if (!storeOrder.getUid().equals(currentUser.getUid())) {
            if("en".equals(language)){
                throw new VcaException("The order does not match the logged in user");
            }else{
                throw new VcaException("该订单与登录用户不匹配");
            }
        }

        BeanUtils.copyProperties(storeOrder, storeOrderDetailResponse);
        //订单类型
        storeOrderDetailResponse.setOrderNo(storeOrder.getOrderId());
        storeOrderDetailResponse.setOrderType(getOrderActivityType(language,storeOrder));


//        MyRecord orderStatusVo = getOrderStatusVo(storeOrder);

        //订单详情//
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, storeOrderDetailResponse.getOrderNo()));

        //已退款数量
        Integer refund = 0;
        //退款中数量
        Integer underRefund = 0;
        //商品详情
        List<PreOrderCommonVo.PreOrderProductDetail> preOrderProductDetail = new ArrayList<>();

        HashMap<Long, String> integerIntegerHashMap = new HashMap<>();
        //System.out.println(storeOrderInfoList+"========");
        for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
            //System.out.println(storeOrderInfo+"----------");
            //预约人信息
            storeOrderDetailResponse.setIsAppointedBy(storeOrder.getUid().equals(storeOrderInfo.getLecturer()) ? 1 : 0);
            storeOrderDetailResponse.setLecturerName(storeOrderInfo.getLecturerName());
            storeOrderDetailResponse.setLecturer(storeOrderInfo.getLecturer());
            storeOrderDetailResponse.setLecturerPhone(storeOrderInfo.getLecturerPhone());
            storeOrderDetailResponse.setLecturerEmail(storeOrderInfo.getLecturerEmail());


            //PreOrderCommonVo.PreOrderProductDetail infoAll = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.PreOrderProductDetail.class);
            //PreOrderCommonVo.CourseInfoDetail courseInfoDetailAll = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.CourseInfoDetail.class);
            //System.out.println(storeOrderInfo.getInfo()+"=====");
            //System.out.println(infoAll+"======");
            //System.out.println(courseInfoDetailAll+"=======");

            if (storeOrderInfo.getType().equals(4)) {
                VcaProduct vcaProduct = vcaProductService.getById(storeOrderInfo.getProductId());
                storeOrderDetailResponse.setIsGiftCard(vcaProduct.getCid().equals(750) ? 1 : 0);
                storeOrderDetailResponse.setProductId(storeOrderInfo.getProductId());
                System.out.println(storeOrderInfo.getInfo()+"-------------");

                PreOrderCommonVo.PreOrderProductDetail detail = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.PreOrderProductDetail.class);
                if("en".equals(language)){
                    detail.setSku(detail.getSkuEn());
                    detail.setName(detail.getNameEn());
                    detail.setType(detail.getTypeEn());
                }

                detail.setRefundStatus(storeOrderInfo.getRefundStatus());
                System.out.println(detail+"==============");
                preOrderProductDetail.add(detail);
            } else {
                if (storeOrderInfo.getType().equals(2)) {
                    Talk talk = talkService.getById(storeOrderInfo.getMainId());
                    if (ObjectUtil.isNull(talk)) {
                        if("en".equals(language)){
                            throw new VcaException("The lecture does not exist");
                        }else{
                            throw new VcaException("该讲座不存在");
                        }

                    }
                    //线上讲座返回直播相关信息
//                    if (talk.getTalkType().equals(2)){
//                        TalkScheduling talkScheduling = talkSchedulingService.getById(storeOrderInfo.getSchedulingId());
//                        if (ObjectUtil.isNull(talkScheduling)){
//                            throw new VcaException("该讲座排期不存在");
//                        }
//                        storeOrderDetailResponse.setLiveStatus(talkScheduling.getLiveStatus());
//                        storeOrderDetailResponse.setLiveLink(ObjectUtil.isNull(talkScheduling.getLiveId()) ? null : systemConfigService.getValueByKey(Constants.VHALL_LINK) + talkScheduling.getLiveId());
//                        storeOrderDetailResponse.setViewingPlatformName(talk.getViewingPlatformName());
//                    }

                    storeOrderDetailResponse.setTalkType(talk.getTalkType());

                }

                if (storeOrderInfo.getType().equals(1)){
                    integerIntegerHashMap.put(storeOrderInfo.getTaokeAboutCourseId(), getOrderInfoStatus(language,storeOrderInfo));
                }else {
                    integerIntegerHashMap.put(storeOrderInfo.getMainId(), getOrderInfoStatus(language,storeOrderInfo));
                }
                storeOrderDetailResponse.setMainId(storeOrderInfo.getMainId());
                PreOrderCommonVo.CourseInfoDetail courseInfoDetail = JSONObject.parseObject(storeOrderInfo.getInfo(), PreOrderCommonVo.CourseInfoDetail.class);
                if("en".equals(language)){
                    courseInfoDetail.setName(courseInfoDetail.getNameEn());
                    courseInfoDetail.setTypeName(courseInfoDetail.getTypeNameEn());
                }
                System.out.println(courseInfoDetail.getSchedulings()+"------------");

                for (PreOrderCommonVo.CourseInfoDetail.Scheduling scheduling : courseInfoDetail.getSchedulings()) {
                    if("en".equals(language)){
                        if(scheduling.getCourseNameEn() != null && !scheduling.getCourseNameEn().isEmpty()){
                            scheduling.setCourseName(scheduling.getCourseNameEn());
                        }

                        if(scheduling.getLanguageEn() != null && !scheduling.getLanguageEn().isEmpty()){
                            scheduling.setLanguage(scheduling.getLanguageEn());
                        }

                        if(scheduling.getCourseAddressEn() != null && !scheduling.getCourseAddressEn().isEmpty()){
                            scheduling.setCourseAddress(scheduling.getCourseAddressEn());
                        }



                    }
                    //不为空则为套课
                    if (ObjectUtil.isNotNull(scheduling.getCourseId())) {
                        scheduling.setOrderInfoStatus(integerIntegerHashMap.get(scheduling.getCourseId()));
                        scheduling.setPayPrice(storeOrderInfo.getPayPrice());
                    } else {
                        scheduling.setOrderInfoStatus(integerIntegerHashMap.get(courseInfoDetail.getMainId()));
                        scheduling.setPayPrice(storeOrderInfo.getPayPrice());
                    }
                }

                System.out.println(courseInfoDetail+"============");
                storeOrderDetailResponse.setCourseInfoDetails(courseInfoDetail);
            }

            //已退款的订单
            if (storeOrderInfo.getRefundStatus().equals(2)){
                refund = refund +1;
            }
            //退款中的订单
            if (storeOrderInfo.getRefundStatus().equals(1) || storeOrderInfo.getRefundStatus().equals(3) || storeOrderInfo.getRefundStatus().equals(4) || storeOrderInfo.getRefundStatus().equals(5)){
                underRefund = underRefund +1;
            }
        }

        if (refund.equals(storeOrderInfoList.size()) || underRefund.equals(storeOrderInfoList.size())){
            storeOrderDetailResponse.setIsAllRefund(1);
        }else {
            //套课一个已退款也是已全部退款 前端页面也是已取消
            if (storeOrder.getType().equals(1) && (storeOrder.getRefundStatus().equals(2) || storeOrder.getRefundStatus().equals(3))) {
                storeOrderDetailResponse.setIsAllRefund(1);
            }
            storeOrderDetailResponse.setIsAllRefund(0);
        }
        // 订单状态
        storeOrderDetailResponse.setOrderStatus(getH5OrderStatus(language,storeOrder,storeOrderInfoList));

        storeOrderDetailResponse.setPreOrderProductDetails(preOrderProductDetail);
        System.out.println(storeOrderDetailResponse+"--------");
        if (!storeOrder.getType().equals(4)) {
            //一年内是否退款
            Integer userId = userService.getUserId();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.YEAR, -1);
            Date y = c.getTime();
            String year = format.format(y);
            LambdaQueryWrapper<StoreOrder> storeOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            storeOrderLambdaQueryWrapper.in(StoreOrder::getRefundStatus, 1, 2, 3);
            storeOrderLambdaQueryWrapper.in(StoreOrder::getType, 0, 1, 2, 3);
            storeOrderLambdaQueryWrapper.eq(StoreOrder::getPaid, 2);
            storeOrderLambdaQueryWrapper.eq(StoreOrder::getUid, userId);
            storeOrderLambdaQueryWrapper.gt(StoreOrder::getRefundReasonTime, y);
            List<StoreOrder> list = storeOrderService.list(storeOrderLambdaQueryWrapper);

            List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, storeOrder.getOrderId()).orderByAsc(StoreOrderInfo::getSchedulingDate, StoreOrderInfo::getSchedulingStartTime));


            String time = storeOrderInfos.get(0).getSchedulingDate() + " " + storeOrderInfos.get(0).getSchedulingStartTime() + ":00";
            //预约时间
            Date date = null;
            //当前时间
            Date currentTime = null;
            String cancelIime = "";
            if (storeOrder.getType().equals(0) || storeOrder.getType().equals(1)) {
                cancelIime = systemConfigService.getValueByKey("course_cancel_time");
            } else if (storeOrder.getType().equals(2)) {
                cancelIime = systemConfigService.getValueByKey("talk_cancel_time");
            } else if (storeOrder.getType().equals(3)) {
                cancelIime = systemConfigService.getValueByKey("exhibition_cancel_time");
            }
            try {
                date = format.parse(time);
                currentTime = format.parse(format.format(new Date()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long dayM = 1000 * 24 * 60 * 60;
            long hourM = 1000 * 60 * 60;
            long differ = date.getTime() - currentTime.getTime();
            long hour = differ % dayM / hourM + 24 * (differ / dayM); //预约时间减去当前时间毫秒数
            if (list.size() == 0) { //如果一年内有过退款
                storeOrderDetailResponse.setIsRefund(0);
            } else {
                storeOrderDetailResponse.setIsRefund(1);
            }

            //是否已过指定时间
            if (hour > Integer.parseInt(cancelIime)) {
                storeOrderDetailResponse.setIsTimeElapsed(0);
            } else {
                storeOrderDetailResponse.setIsTimeElapsed(1);
            }

        }

        //剩余付款时间
        if (!storeOrder.getPaid() && !storeOrder.getIsDel() && !storeOrder.getIsSystemDel()){
            String cancelStr = null;
            switch (storeOrder.getType()) {
                //0-课程订单
                case 0:
                    cancelStr = systemConfigService.getValueByKey(Constants.COURSE_CANCEL_TIME);
                    break;
                //1=套课订单
                case 1:
                    cancelStr = systemConfigService.getValueByKey(Constants.COURSE_CANCEL_TIME);
                    break;
                //2=讲座订单
                case 2:
                    cancelStr = systemConfigService.getValueByKey(Constants.TALK_CANCEL_TIME);
                    break;
                //3=展览订单
                case 3:
                    cancelStr = systemConfigService.getValueByKey(Constants.EXHIBITION_CANCEL_TIME);
                    break;
                // 4=商品订单
                case 4:
                    cancelStr = systemConfigService.getValueByKey(Constants.ORDER_CANCEL_TIME);
                    break;
                default:
                    break;
            }

//            String orderCancelTime = systemConfigService.getValueByKey(Constants.ORDER_CANCEL_TIME);//分钟
            //创建订单时间
            Date createTime = storeOrder.getCreateTime();

            Date date = DateUtils.addMinutes(createTime, Integer.parseInt(cancelStr));

            storeOrderDetailResponse.setUnpaidCountdown(date.getTime());
        }
        //物流信息
        if (storeOrder.getType().equals(4) && storeOrder.getStatus() > 0 && storeOrderDetailResponse.getIsGiftCard().equals(0) && StringUtils.isNotEmpty(storeOrder.getMasterWaybillNo())) {
            ResponseCancel orderRouting = sfService.getOrderRouting(language,storeOrderDetailResponse.getOrderNo(),1);
            if (ObjectUtil.isNotEmpty(orderRouting) && ObjectUtil.isNotEmpty(orderRouting.getMsgData())){
                Map<String, Object> innerMap = orderRouting.getMsgData().getInnerMap();
                JSONArray jsonArray = (JSONArray) innerMap.get("routeResps");
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                JSONArray routes = (JSONArray) jsonObject.get("routes");
                if (ObjectUtil.isNotEmpty(routes)){
                    List<Routes> routesList = JSONObject.parseArray(routes.toJSONString(), Routes.class);
                    List<Routes> collect = routesList.stream().sorted(Comparator.comparing(Routes::getAcceptTime).reversed()).collect(Collectors.toList());
                    storeOrderDetailResponse.setRoutes(collect.get(0));
                }else{
                    Routes route = new Routes();
                    if("en".equals(language)){
                        route.setRemark("Not picked up or shipped for more than 3 months!");
                    }else{
                        route.setRemark("未揽收或寄件时间超过3个月！");
                    }

                    storeOrderDetailResponse.setRoutes(route);
                }
            }
        }


        //是否已过申请售后时间
        Date afterSalesDeadline = storeOrder.getAfterSalesDeadline();
        if (ObjectUtil.isNotNull(afterSalesDeadline)){
            if (new Date().getTime()<afterSalesDeadline.getTime()){
                storeOrderDetailResponse.setIsAfterSalesTime(false);
            }else {
                storeOrderDetailResponse.setIsAfterSalesTime(true);
            }
        }

//        storeOrderDetailResponse.setOrderStatusMsg(orderStatusVo.getStr("msg"));
//        storeOrderDetailResponse.setPayTypeStr(orderStatusVo.getStr("payTypeStr"));
//        BigDecimal proTotalPrice = storeOrderDetailResponse.getPayPrice().add(storeOrderDetailResponse.getCouponPrice()).add(storeOrderDetailResponse.getDeductionPrice());
//        storeOrderDetailResponse.setProTotalPrice(proTotalPrice);
        return storeOrderDetailResponse;
    }

    private String getOrderInfoStatus(String language,StoreOrderInfo storeOrderInfo) {
        StoreOrder storeOrder = storeOrderService.getByOrderId(storeOrderInfo.getOrderNo());
        if (!storeOrder.getPaid()) {
            if("en".equals(language)){
                return "未支付";
            }else{
                return "Unpaid";
            }
        }
        if (storeOrder.getIsDel() || storeOrder.getIsSystemDel()) {
            if("en".equals(language)){
                return "Canceled";
            }else{
                return "已取消";
            }
        }
        if (storeOrderInfo.getRefundStatus().equals(1)) {
            if("en".equals(language)){
                return "Applying for a refund";
            }else{
                return "申请退款中";
            }
        }
        if (storeOrderInfo.getRefundStatus().equals(4)) {
            if("en".equals(language)){
                return "To be returned";
            }else{
                return "待退货";
            }
        }
        if (storeOrderInfo.getRefundStatus().equals(5)) {
            if("en".equals(language)){
                return "Returning goods";
            }else{
                return "退货中";
            }
        }
        if (storeOrderInfo.getRefundStatus().equals(2)) {
            if("en".equals(language)){
                return "Refunded";
            }else{
                return "已退款";
            }
        }
        if (storeOrderInfo.getRefundStatus().equals(3)) {
            if("en".equals(language)){
                return "Being refunded";
            }else{
                return "退款中";
            }
        }
        if (storeOrderInfo.getStatus().equals(0)) {
            if("en".equals(language)){
                return "Goods waiting to be sent";
            }else{
                return "待发货";
            }
        }
        if (storeOrderInfo.getStatus().equals(1)) {
            if (storeOrderInfo.getType().equals(4)) {
                if("en".equals(language)){
                    return "Wait to be received";
                }else{
                    return "待收货";
                }
            } else {
                if("en".equals(language)){
                    return "To be written off";
                }else{
                    return "待核销";
                }
            }
        }
        if (storeOrderInfo.getStatus().equals(2)) {
            if("en".equals(language)){
                return "Remain to be evaluated";
            }else{
                return "待评价";
            }
        }
        if (storeOrderInfo.getStatus().equals(3) || storeOrderInfo.getRefundStatus().equals(6)) {
            if("en".equals(language)){
                return "Completed";
            }else{
                return "已完成";
            }
        }
        return "";
    }

    /**
     * 获取订单状态相关信息
     *
     * @return MyRecord
     */
    private MyRecord getOrderStatusVo(StoreOrder storeOrder) {
        MyRecord record = new MyRecord();
        if (!storeOrder.getPaid()) {
            record.set("type", 0);
            record.set("title", "未支付");
            record.set("msg", "订单未支付");
            List<String> configKeys = new ArrayList<>();
            configKeys.add("order_cancel_time");
            configKeys.add("order_activity_time");
            configKeys.add("order_bargain_time");
            configKeys.add("order_seckill_time");
            configKeys.add("order_pink_time");
            List<String> configValues = systemConfigService.getValuesByKes(configKeys);
            Date timeSpace;
            timeSpace = DateUtil.addSecond(storeOrder.getCreateTime(), Double.valueOf(configValues.get(0)).intValue() * 3600);
            record.set("msg", "请在" + DateUtil.dateToStr(timeSpace, Constants.DATE_FORMAT) + "前完成支付");
        } else if (storeOrder.getRefundStatus() == 1) {
            record.set("type", -1);
            record.set("title", "申请退款中");
            record.set("msg", "商家审核中,请耐心等待");
        } else if (storeOrder.getRefundStatus() == 2) {
            record.set("type", -2);
            record.set("title", "已退款");
            record.set("msg", "已为您退款,感谢您的支持");
        } else if (storeOrder.getRefundStatus() == 3) {
            record.set("type", -3);
            record.set("title", "退款中");
            record.set("msg", "正在为您退款,感谢您的支持");
        } else if (storeOrder.getStatus() == 0) {
            record.set("type", 1);
            record.set("title", "未发货");
            record.set("msg", "商家未发货,请耐心等待");
        } else if (storeOrder.getStatus() == 1) { // 待收货处理
            // 待收货
            if (null != storeOrder.getDeliveryType() && storeOrder.getDeliveryType().equals(Constants.ORDER_STATUS_STR_SPIKE_KEY)) { // 送货
                StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
                storeOrderStatus.setOid(storeOrder.getId());
                storeOrderStatus.setChangeType(Constants.ORDER_LOG_DELIVERY);
                List<StoreOrderStatus> sOrderStatusResults = storeOrderStatusService.getByEntity(storeOrderStatus);
                if (sOrderStatusResults.size() > 0) {
                    record.set("type", 2);
                    record.set("title", "待收货");
                    record.set("msg", "商家已送货,请耐心等待");
                }
            } else if (null != storeOrder.getDeliveryType() && storeOrder.getDeliveryType().equals(Constants.ORDER_LOG_EXPRESS)) {
                StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
                storeOrderStatus.setOid(storeOrder.getId());
                storeOrderStatus.setChangeType(Constants.ORDER_LOG_EXPRESS);
                List<StoreOrderStatus> sOrderStatusResults = storeOrderStatusService.getByEntity(storeOrderStatus);
                if (sOrderStatusResults.size() > 0) {
                    record.set("type", 2);
                    record.set("title", "待收货");
                    record.set("msg", "商家已发货,请耐心等待");
                }
            } else {
                StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
                storeOrderStatus.setOid(storeOrder.getId());
                storeOrderStatus.setChangeType(Constants.ORDER_LOG_DELIVERY_VI);
                List<StoreOrderStatus> sOrderStatusResults = storeOrderStatusService.getByEntity(storeOrderStatus);
                if (sOrderStatusResults.size() > 0) {
                    record.set("type", 2);
                    record.set("title", "待收货");
                    record.set("msg", "服务商已虚拟发货");
                } else {
                    record.set("type", 2);
                    record.set("title", "待收货");
                    record.set("msg", "退款拒绝订单已发货");
                }
            }
        } else if (storeOrder.getStatus() == 2) {
            record.set("type", 3);
            record.set("title", "待评价");
            record.set("msg", "已收货,快去评价一下吧");
        } else if (storeOrder.getStatus() == 3) {
            record.set("type", 4);
            record.set("title", "交易完成");
            record.set("msg", "交易完成,感谢您的支持");
        }

        // 支付方式
        String orderPayTypeStr = orderUtils.getOrderPayTypeStr(storeOrder.getPayType());
        record.set("payTypeStr", orderPayTypeStr);
        if (StringUtils.isNotBlank(storeOrder.getDeliveryType())) {
            record.set("deliveryType", StringUtils.isNotBlank(storeOrder.getDeliveryType()) ? storeOrder.getDeliveryType() : "其他方式");
        }

        // 获取商品状态图片 ignore
//        List<SystemGroupDataOrderStatusPicResponse> orderStatusPicList = systemGroupDataService.getListByGid(SysGroupDataConstants.GROUP_DATA_ID_ORDER_STATUS_PIC, SystemGroupDataOrderStatusPicResponse.class);// 53 = group id 在groupData中查询数据
//        for (SystemGroupDataOrderStatusPicResponse picList : orderStatusPicList) {
//            if (picList.getOrderStatus() == record.getInt("type")) {
//                record.set("statusPic", picList.getUrl());
//                break;
//            }
//        }
        return record;
    }

    /**
     * 订单tap data
     *
     * @return 订单状态数据量
     */
    @Override
    public OrderDataResponse orderData() {
        Integer userId = userService.getUserIdException();
        OrderDataResponse result = new OrderDataResponse();

        // 订单数量
        Integer orderCount = storeOrderService.getOrderCountByUid(userId);
        // 待支付订单数
        Integer unPaidCount = storeOrderService.getTopDataUtil(Constants.ORDER_STATUS_H5_UNPAID, userId);

        if (orderCount.equals(0)) {
            result.setOrderCount(0);
            result.setSumPrice(BigDecimal.ZERO);
            result.setUnPaidCount(unPaidCount);
            result.setUnShippedCount(0);
            result.setReceivedCount(0);
            result.setEvaluatedCount(0);
            result.setCompleteCount(0);
            result.setRefundCount(0);
            return result;
        }

        result.setOrderCount(orderCount);
        // 总消费金额
        BigDecimal sumPrice = storeOrderService.getSumPayPriceByUid(userId);
        result.setSumPrice(sumPrice);
        // 未支付
        result.setUnPaidCount(unPaidCount);
        // 待发货
        result.setUnShippedCount(storeOrderService.getTopDataUtil(Constants.ORDER_STATUS_H5_NOT_SHIPPED, userId));
        // 待收货
        result.setReceivedCount(storeOrderService.getTopDataUtil(Constants.ORDER_STATUS_H5_SPIKE, userId));
        // 待核销
        result.setEvaluatedCount(storeOrderService.getTopDataUtil(Constants.ORDER_STATUS_H5_JUDGE, userId));
        // 已完成
        result.setCompleteCount(storeOrderService.getTopDataUtil(Constants.ORDER_STATUS_H5_COMPLETE, userId));
        // 退款中和已退款（只展示退款中）
        result.setRefundCount(storeOrderService.getTopDataUtil(Constants.ORDER_STATUS_H5_REFUNDING, userId));
        return result;
    }

    /**
     * 查询退款理由
     *
     * @return 退款理由集合
     */
    @Override
    public List<String> getRefundReason() {
        String reasonString = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_STOR_REASON);
        reasonString = VcaUtil.UnicodeToCN(reasonString);
        reasonString = reasonString.replace("rn", "n");
        return Arrays.asList(reasonString.split("\\n"));
    }


    /**
     * 获取待评价信息
     */
    @Override
    public OrderProductReplyResponse getReplyProduct(GetProductReply productReply) {
        StoreOrderInfo storeOrderInfo = storeOrderInfoService.getByUniAndOrderId(productReply.getUni(), productReply.getOrderNo());
        OrderInfoDetailVo scr = JSONObject.parseObject(storeOrderInfo.getInfo(), OrderInfoDetailVo.class);
        OrderProductReplyResponse response = new OrderProductReplyResponse();
        response.setCartNum(scr.getPayNum());
        response.setTruePrice(scr.getPrice());
        response.setProductId(scr.getProductId());
        response.setImage(scr.getImage());
        response.setSku(scr.getSku());
        response.setStoreName(scr.getProductName());
        return response;
    }

    /**
     * 获取申请订单退款信息
     *
     * @param orderNo 订单编号
     * @return ApplyRefundOrderInfoResponse
     */
    @Override
    public ApplyRefundOrderInfoResponse applyRefundOrderInfo(String language,String orderNo) {
        User info = userService.getInfo();
        //订单
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderNo);

        //子订单信息
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.getListByOrderNo(orderNo);
        //商品信息
        VcaProduct vcaProduct = vcaProductService.getById(storeOrderInfoList.get(0).getProductId());
        //是否已过申请售后时间
        Date afterSalesDeadline = storeOrder.getAfterSalesDeadline();
        if (ObjectUtil.isEmpty(storeOrder)){
            throw new VcaException("en".equals(language) ? "The order does not exist" : "该订单不存在");
        }

        if (!Objects.equals(storeOrder.getUid(),info.getUid())){
            throw new VcaException("en".equals(language) ? "The order does not exist" : "该订单不存在");
        }
        if (ObjectUtil.isNull(afterSalesDeadline)){
            throw new VcaException("en".equals(language) ? "The deadline for after-sales service is empty" : "售后截止时间为空");
        }
        if (new Date().getTime()>afterSalesDeadline.getTime()&& !vcaProduct.getCid().equals(750)){
            throw new VcaException("en".equals(language) ? "Order Past After-sales Period" : "订单已超售后有效期");
        }
        if (storeOrder.getRefundStatus()>0){
            throw new VcaException("en".equals(language) ? "Already Applied, No Repeats" : "已申请过，不可重复申请");
        }

        if (storeOrderInfoList.get(0).getProductId() == null){
            throw new VcaException("en".equals(language) ? "The product does not exist" : "该商品不存在");
        }




        ApplyRefundOrderInfoResponse response = new ApplyRefundOrderInfoResponse();
        response.setOrderNo(storeOrder.getOrderId());
        response.setId(storeOrder.getId());
        //申请理由
        String storReason = systemConfigService.getValueByKey("en".equals(language) ? Constants.STOR_REASON_EN : Constants.STOR_REASON);
        response.setRefundReasonWap(storReason);

        ArrayList<OrderRefundVo> orderRefundVos = new ArrayList<>();
        for (StoreOrderInfo storeOrderInfo : storeOrderInfoList) {
            OrderRefundVo orderRefundVo = new OrderRefundVo();
//            //如果是礼品卡则给礼品卡状态赋值
//            if (vcaProduct.getCid().equals(750)){
//                List<UserCard> userCards = userCardService.list(new LambdaQueryWrapper<UserCard>().eq(UserCard::getOrderId, storeOrderInfo.getMerOrderNo()));
//                for (UserCard userCard : userCards) {
//
//                }
//                orderRefundVo.setStatus(userCard.getStutus());
//            }
            if("en".equals(language)){
                storeOrderInfo.setName(storeOrderInfo.getNameEn());
            }

            BeanUtils.copyProperties(storeOrderInfo, orderRefundVo);
            orderRefundVo.setImagePath(storeOrderInfo.getImage());
            orderRefundVo.setUnitPrice(storeOrderInfo.getPrice());
            orderRefundVo.setQuantity(storeOrderInfo.getPayNum());
            orderRefundVos.add(orderRefundVo);
        }
        response.setOrderRefundVoList(orderRefundVos);
        return response;
    }

    @Override
    public ComputedOrderPriceResponse computedOrderPrice(OrderComputedPriceRequest request) {
        return null;
    }


    /**
     * 获取支付配置
     *
     * @return PreOrderResponse
     */
    @Override
    public PreOrderResponse getPayConfig() {
        PreOrderResponse preOrderResponse = new PreOrderResponse();
        String payWeixinOpen = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_PAY_WEIXIN_OPEN);
        String yuePayStatus = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_YUE_PAY_STATUS);// 1开启 2关闭
        String storeSelfMention = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_STORE_SELF_MENTION);
        String aliPayStatus = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_ALI_PAY_STATUS);// 1开启
        preOrderResponse.setYuePayStatus(yuePayStatus);
        preOrderResponse.setPayWeixinOpen(payWeixinOpen);
        preOrderResponse.setStoreSelfMention(storeSelfMention);
        preOrderResponse.setAliPayStatus(aliPayStatus);
        return preOrderResponse;
    }

    /**
     * 校验商品库存（生成订单）
     *
     * @param orderInfoVo 订单详情Vo
     * @return List<MyRecord>
     * skuRecord 扣减库存对象
     * ——activityId             活动商品id
     * ——activityAttrValueId    活动商品skuId
     * ——productId              普通（主）商品id
     * ——attrValueId            普通（主）商品skuId
     * ——num                    购买数量
     */
    private List<MyRecord> validateProductStock(OrderInfoVo orderInfoVo, User user) {
        List<MyRecord> recordList = CollUtil.newArrayList();
        if (orderInfoVo.getSeckillId() > 0) {
            // 秒杀部分判断
            Integer seckillId = orderInfoVo.getSeckillId();
            OrderInfoDetailVo detailVo = orderInfoVo.getOrderDetailList().get(0);
//            StoreSeckill storeSeckill = storeSeckillService.getByIdException(seckillId);
            StoreProductAttrValue seckillAttrValue = storeProductAttrValueService.getByIdAndProductIdAndType(detailVo.getAttrValueId(), seckillId, Constants.PRODUCT_TYPE_SECKILL);
            if (ObjectUtil.isNull(seckillAttrValue)) {
                throw new VcaException("秒杀商品规格不存在");
            }
//            MyRecord seckillRecord = commonValidateSeckill(storeSeckill, seckillAttrValue, user, detailVo.getPayNum());
            // 主商品sku
//            StoreProductAttrValue productAttrValue = seckillRecord.get("productAttrValue");

            MyRecord record = new MyRecord();
            record.set("activityId", seckillId);
            record.set("activityAttrValueId", seckillAttrValue.getId());
//            record.set("productId", storeSeckill.getProductId());
//            record.set("attrValueId", productAttrValue.getId());
            record.set("num", detailVo.getPayNum());
            recordList.add(record);
            return recordList;
        }
        if (orderInfoVo.getBargainId() > 0) {
            // 砍价部分判断
            Integer bargainId = orderInfoVo.getBargainId();
            OrderInfoDetailVo detailVo = orderInfoVo.getOrderDetailList().get(0);
//            StoreBargain storeBargain = storeBargainService.getByIdException(bargainId);
//            if (storeBargain.getStock().equals(0) || detailVo.getPayNum() > storeBargain.getStock()) {
//                throw new VcaException("砍价商品库存不足");
//            }
            StoreProductAttrValue bargainAttrValue = storeProductAttrValueService.getByIdAndProductIdAndType(detailVo.getAttrValueId(), bargainId, Constants.PRODUCT_TYPE_BARGAIN);
            if (ObjectUtil.isNull(bargainAttrValue)) {
                throw new VcaException("砍价商品规格不存在");
            }
//            MyRecord bargainRecord = commonValidateBargain(storeBargain, bargainAttrValue, orderInfoVo.getBargainUserId(), user, detailVo.getPayNum());
//            StoreProductAttrValue productAttrValue = bargainRecord.get("productAttrValue");

            MyRecord record = new MyRecord();
            record.set("activityId", bargainId);
            record.set("activityAttrValueId", bargainAttrValue.getId());
//            record.set("productId", storeBargain.getProductId());
//            record.set("attrValueId", productAttrValue.getId());
            record.set("num", detailVo.getPayNum());
            recordList.add(record);
            return recordList;
        }
        if (orderInfoVo.getCombinationId() > 0) {
            // 拼团部分判断
            Integer combinationId = orderInfoVo.getCombinationId();
            OrderInfoDetailVo detailVo = orderInfoVo.getOrderDetailList().get(0);
//            StoreCombination storeCombination = storeCombinationService.getByIdException(combinationId);
            StoreProductAttrValue combinationAttrValue = storeProductAttrValueService.getByIdAndProductIdAndType(detailVo.getAttrValueId(), combinationId, Constants.PRODUCT_TYPE_PINGTUAN);
            if (ObjectUtil.isNull(combinationAttrValue)) {
                throw new VcaException("拼团商品规格不存在");
            }
//            MyRecord combinationRecord = commonValidateCombination(storeCombination, combinationAttrValue, user, detailVo.getPayNum());
//            StoreProductAttrValue productAttrValue = combinationRecord.get("productAttrValue");

            MyRecord record = new MyRecord();
            record.set("activityId", combinationId);
            record.set("activityAttrValueId", combinationAttrValue.getId());
//            record.set("productId", storeCombination.getProductId());
//            record.set("attrValueId", productAttrValue.getId());
            record.set("num", detailVo.getPayNum());
            recordList.add(record);
            return recordList;
        }
        // 普通商品
        List<OrderInfoDetailVo> orderDetailList = orderInfoVo.getOrderDetailList();
        orderDetailList.forEach(e -> {
            // 查询商品信息
            StoreProduct storeProduct = storeProductService.getById(e.getProductId());
            if (ObjectUtil.isNull(storeProduct)) {
                throw new VcaException("购买的商品信息不存在");
            }
            if (storeProduct.getIsDeleted()) {
                throw new VcaException("购买的商品已删除");
            }
            if (!storeProduct.getIsShow()) {
                throw new VcaException("购买的商品已下架");
            }
            if (storeProduct.getStock().equals(0) || e.getPayNum() > storeProduct.getStock()) {
                throw new VcaException("购买的商品库存不足");
            }
            // 查询商品规格属性值信息
            StoreProductAttrValue attrValue = attrValueService.getByIdAndProductIdAndType(e.getAttrValueId(), e.getProductId(), Constants.PRODUCT_TYPE_NORMAL);
            if (ObjectUtil.isNull(attrValue)) {
                throw new VcaException("购买的商品规格信息不存在");
            }
            if (attrValue.getStock() < e.getPayNum()) {
                throw new VcaException("购买的商品库存不足");
            }
            MyRecord record = new MyRecord();
            record.set("productId", e.getProductId());
            record.set("num", e.getPayNum());
            record.set("attrValueId", e.getAttrValueId());
            recordList.add(record);
        });
        return recordList;
    }


    /**
     * 校验预下单商品信息
     *
     * @param request 预下单请求参数
     * @return OrderInfoVo
     */
    private OrderInfoVo validatePreOrderRequest(PreOrderRequest request, User user) {
       return null;
    }



    /**
     * 再次下单预下单校验
     *
     * @param detailRequest 请求参数
     * @return List<OrderInfoDetailVo>
     */
    private List<OrderInfoDetailVo> validatePreOrderAgain(PreOrderDetailRequest detailRequest, User user) {
        List<OrderInfoDetailVo> detailVoList = CollUtil.newArrayList();
        if (StrUtil.isBlank(detailRequest.getOrderNo())) {
            throw new VcaException("再次购买订单编号不能为空");
        }
        StoreOrder storeOrder = getByOrderIdException(detailRequest.getOrderNo());
        if (storeOrder.getRefundStatus() > 0 || storeOrder.getStatus() != 3) {
            throw new VcaException("只有已完成状态订单才能再次购买");
        }
//        if (storeOrder.getSeckillId() > 0 || storeOrder.getBargainId() > 0 || storeOrder.getCombinationId() > 0) {
//            throw new VcaException("活动商品订单不能再次购买");
//        }
        if (storeOrder.getType().equals(1)) {
            throw new VcaException("视频订单不能再次购买");
        }
        // 获取订单详情
        List<StoreOrderInfoVo> infoVoList = storeOrderInfoService.getVoListByOrderId(storeOrder.getOrderId());
        if (CollUtil.isEmpty(infoVoList)) {
            throw new VcaException("订单详情未找到");
        }
//        SystemUserLevel userLevel = null;
//        if (user.getLevel() > 0) {
//            userLevel = systemUserLevelService.getByLevelId(user.getLevel());
//        }
//        SystemUserLevel finalUserLevel = userLevel;
        infoVoList.forEach(e -> {
            OrderInfoDetailVo detailVo = e.getInfo();
            // 查询商品信息
            StoreProduct storeProduct = storeProductService.getById(detailVo.getProductId());
            if (ObjectUtil.isNull(storeProduct)) {
                throw new VcaException("商品信息不存在，请刷新后重新选择");
            }
            if (storeProduct.getIsDeleted()) {
                throw new VcaException("商品已删除，请刷新后重新选择");
            }
            if (!storeProduct.getIsShow()) {
                throw new VcaException("商品已下架，请刷新后重新选择");
            }
            if (storeProduct.getStock() < detailVo.getPayNum()) {
                throw new VcaException("商品库存不足，请刷新后重新选择");
            }
            // 查询商品规格属性值信息
            StoreProductAttrValue attrValue = attrValueService.getByIdAndProductIdAndType(detailVo.getAttrValueId(), detailVo.getProductId(), Constants.PRODUCT_TYPE_NORMAL);
            if (ObjectUtil.isNull(attrValue)) {
                throw new VcaException("商品规格信息不存在，请刷新后重新选择");
            }
            if (attrValue.getStock() < detailVo.getPayNum()) {
                throw new VcaException("商品规格库存不足，请刷新后重新选择");
            }
            OrderInfoDetailVo tempDetailVo = new OrderInfoDetailVo();
            tempDetailVo.setProductId(storeProduct.getId());
            tempDetailVo.setProductName(storeProduct.getStoreName());
            tempDetailVo.setAttrValueId(attrValue.getId());
            tempDetailVo.setSku(attrValue.getSuk());
            tempDetailVo.setPrice(attrValue.getPrice());
            tempDetailVo.setPayNum(detailVo.getPayNum());
            tempDetailVo.setImage(StrUtil.isNotBlank(attrValue.getImage()) ? attrValue.getImage() : storeProduct.getImage());
            tempDetailVo.setVolume(attrValue.getVolume());
            tempDetailVo.setWeight(attrValue.getWeight());
            tempDetailVo.setTempId(storeProduct.getTempId());
            tempDetailVo.setGiveIntegral(storeProduct.getGiveIntegral());
            tempDetailVo.setIsSub(storeProduct.getIsSub());
            tempDetailVo.setProductType(Constants.PRODUCT_TYPE_NORMAL);
            tempDetailVo.setVipPrice(attrValue.getPrice());
//            if (ObjectUtil.isNotNull(finalUserLevel)) {
//                tempDetailVo.setVipPrice(attrValue.getPrice());
//            }
            detailVoList.add(tempDetailVo);
        });
        return detailVoList;
    }

    private StoreOrder getByOrderIdException(String orderId) {
        StoreOrder storeOrder = storeOrderService.getByOrderId(orderId);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new VcaException("订单不存在");
        }
        if (storeOrder.getIsDel() || storeOrder.getIsSystemDel()) {
            throw new VcaException("订单不存在");
        }
        return storeOrder;
    }




    /**
     * 判断该订单是否都申请退款
     *
     * @return
     */
    @Override
    public Boolean getOrderInfoStatusIsAll(Integer RefundStatus, List<String> merOrderNos) {
        //需要退款的商品
        List<StoreOrderInfo> storeOrderInfoByRefund = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().in(StoreOrderInfo::getMerOrderNo, merOrderNos));

        //变更对应状态后的商品数
        List<StoreOrderInfo> storeOrderInfStatus = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, storeOrderInfoByRefund.get(0).getOrderNo()).eq(StoreOrderInfo::getRefundStatus, RefundStatus));

        //所有商品
        List<StoreOrderInfo> storeOrderInfoAll = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().ne(StoreOrderInfo::getOrderNo, storeOrderInfoByRefund.get(0).getOrderNo()));

        //如果所有商品状态一样返回true
        if (storeOrderInfStatus.size() == storeOrderInfoAll.size()) {
            return true;
        }
        return false;
    }
    @Override
    public Long getTime(){
        return System.currentTimeMillis();
    }



}
